@ember-data-mirror/serializer 5.6.0-beta.0 → 5.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/addon-main.cjs +1 -1
  2. package/dist/index.js +1 -306
  3. package/dist/json-api.js +1 -531
  4. package/dist/json.js +1 -6
  5. package/dist/rest.js +1 -1274
  6. package/dist/transform.js +1 -336
  7. package/package.json +7 -24
  8. package/unstable-preview-types/index.d.ts +81 -243
  9. package/unstable-preview-types/json-api.d.ts +2 -512
  10. package/unstable-preview-types/json.d.ts +2 -1091
  11. package/unstable-preview-types/rest.d.ts +2 -568
  12. package/unstable-preview-types/transform.d.ts +3 -10
  13. package/dist/index.js.map +0 -1
  14. package/dist/json-CVTR4xWv.js +0 -1396
  15. package/dist/json-CVTR4xWv.js.map +0 -1
  16. package/dist/json-api.js.map +0 -1
  17. package/dist/json.js.map +0 -1
  18. package/dist/rest.js.map +0 -1
  19. package/dist/transform.js.map +0 -1
  20. package/unstable-preview-types/-private/embedded-records-mixin.d.ts +0 -102
  21. package/unstable-preview-types/-private/embedded-records-mixin.d.ts.map +0 -1
  22. package/unstable-preview-types/-private/transforms/boolean.d.ts +0 -52
  23. package/unstable-preview-types/-private/transforms/boolean.d.ts.map +0 -1
  24. package/unstable-preview-types/-private/transforms/boolean.type-test.d.ts +0 -4
  25. package/unstable-preview-types/-private/transforms/boolean.type-test.d.ts.map +0 -1
  26. package/unstable-preview-types/-private/transforms/date.d.ts +0 -33
  27. package/unstable-preview-types/-private/transforms/date.d.ts.map +0 -1
  28. package/unstable-preview-types/-private/transforms/number.d.ts +0 -34
  29. package/unstable-preview-types/-private/transforms/number.d.ts.map +0 -1
  30. package/unstable-preview-types/-private/transforms/string.d.ts +0 -34
  31. package/unstable-preview-types/-private/transforms/string.d.ts.map +0 -1
  32. package/unstable-preview-types/-private/transforms/transform.d.ts +0 -126
  33. package/unstable-preview-types/-private/transforms/transform.d.ts.map +0 -1
  34. package/unstable-preview-types/-private/utils.d.ts +0 -6
  35. package/unstable-preview-types/-private/utils.d.ts.map +0 -1
  36. package/unstable-preview-types/index.d.ts.map +0 -1
  37. package/unstable-preview-types/json-api.d.ts.map +0 -1
  38. package/unstable-preview-types/json.d.ts.map +0 -1
  39. package/unstable-preview-types/rest.d.ts.map +0 -1
  40. package/unstable-preview-types/transform.d.ts.map +0 -1
@@ -1,1093 +1,4 @@
1
1
  declare module '@ember-data-mirror/serializer/json' {
2
- export default JSONSerializer;
3
- /**
4
- * <blockquote style="margin: 1em; padding: .1em 1em .1em 1em; border-left: solid 1em #E34C32; background: #e0e0e0;">
5
- <p>
6
- ⚠️ <strong>This is LEGACY documentation</strong> for a feature that is no longer encouraged to be used.
7
- If starting a new app or thinking of implementing a new adapter, consider writing a
8
- <a href="/ember-data/release/classes/%3CInterface%3E%20Handler">Handler</a> instead to be used with the <a href="https://github.com/emberjs/data/tree/main/packages/request#readme">RequestManager</a>
9
- </p>
10
- </blockquote>
2
+ export { JSONSerializer as default } from "@warp-drive-mirror/legacy/serializer/json";
11
3
 
12
- In EmberData a Serializer is used to serialize and deserialize
13
- records when they are transferred in and out of an external source.
14
- This process involves normalizing property names, transforming
15
- attribute values and serializing relationships.
16
-
17
- By default, EmberData uses and recommends the `JSONAPISerializer`.
18
-
19
- `JSONSerializer` is useful for simpler or legacy backends that may
20
- not support the http://jsonapi.org/ spec.
21
-
22
- For example, given the following `User` model and JSON payload:
23
-
24
- ```app/models/user.js
25
- import Model, { attr, belongsTo, hasMany } from '@ember-data-mirror/model';
26
-
27
- export default class UserModel extends Model {
28
- @hasMany('user') friends;
29
- @belongsTo('location') house;
30
-
31
- @attr('string') name;
32
- }
33
- ```
34
-
35
- ```js
36
- {
37
- id: 1,
38
- name: 'Sebastian',
39
- friends: [3, 4],
40
- links: {
41
- house: '/houses/lefkada'
42
- }
43
- }
44
- ```
45
-
46
- `JSONSerializer` will normalize the JSON payload to the JSON API format that the
47
- Ember Data store expects.
48
-
49
- You can customize how JSONSerializer processes its payload by passing options in
50
- the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks:
51
-
52
- - To customize how a single record is normalized, use the `normalize` hook.
53
- - To customize how `JSONSerializer` normalizes the whole server response, use the
54
- `normalizeResponse` hook.
55
- - To customize how `JSONSerializer` normalizes a specific response from the server,
56
- use one of the many specific `normalizeResponse` hooks.
57
- - To customize how `JSONSerializer` normalizes your id, attributes or relationships,
58
- use the `extractId`, `extractAttributes` and `extractRelationships` hooks.
59
-
60
- The `JSONSerializer` normalization process follows these steps:
61
-
62
- 1. `normalizeResponse`
63
- - entry method to the serializer.
64
- 2. `normalizeCreateRecordResponse`
65
- - a `normalizeResponse` for a specific operation is called.
66
- 3. `normalizeSingleResponse`|`normalizeArrayResponse`
67
- - for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple records back.
68
- 4. `normalize`
69
- - `normalizeArrayResponse` iterates and calls `normalize` for each of its records while `normalizeSingle`
70
- calls it once. This is the method you most likely want to subclass.
71
- 5. `extractId` | `extractAttributes` | `extractRelationships`
72
- - `normalize` delegates to these methods to
73
- turn the record payload into the JSON API format.
74
-
75
- @main @ember-data-mirror/serializer/json
76
- @class JSONSerializer
77
- @public
78
- @extends Serializer
79
- */
80
- const JSONSerializer: Readonly<typeof Serializer> & (new (owner?: import("@ember/-internals/owner").default) => Serializer) & {
81
- /**
82
- The `primaryKey` is used when serializing and deserializing
83
- data. Ember Data always uses the `id` property to store the id of
84
- the record. The external source may not always follow this
85
- convention. In these cases it is useful to override the
86
- `primaryKey` property to match the `primaryKey` of your external
87
- store.
88
-
89
- Example
90
-
91
- ```app/serializers/application.js
92
- import JSONSerializer from '@ember-data-mirror/serializer/json';
93
-
94
- export default class ApplicationSerializer extends JSONSerializer {
95
- primaryKey = '_id'
96
- }
97
- ```
98
-
99
- @property primaryKey
100
- @type {String}
101
- @public
102
- @default 'id'
103
- */
104
- primaryKey: string;
105
- /**
106
- The `attrs` object can be used to a simple mapping between
107
- property names on `Model` records and payload keys in the
108
- serialized JSON object representing the record. An object with the
109
- property `key` can also be used to designate the attribute's key on
110
- the response payload.
111
-
112
- Example
113
-
114
- ```app/models/person.js
115
- import Model, { attr } from '@ember-data-mirror/model';
116
-
117
- export default class PersonModel extends Model {
118
- @attr('string') firstName;
119
- @attr('string') lastName;
120
- @attr('string') occupation;
121
- @attr('boolean') admin;
122
- }
123
- ```
124
-
125
- ```app/serializers/person.js
126
- import JSONSerializer from '@ember-data-mirror/serializer/json';
127
-
128
- export default class PersonSerializer extends JSONSerializer {
129
- attrs = {
130
- admin: 'is_admin',
131
- occupation: { key: 'career' }
132
- }
133
- }
134
- ```
135
-
136
- You can also remove attributes and relationships by setting the `serialize`
137
- key to `false` in your mapping object.
138
-
139
- Example
140
-
141
- ```app/serializers/person.js
142
- import JSONSerializer from '@ember-data-mirror/serializer/json';
143
-
144
- export default class PostSerializer extends JSONSerializer {
145
- attrs = {
146
- admin: { serialize: false },
147
- occupation: { key: 'career' }
148
- }
149
- }
150
- ```
151
-
152
- When serialized:
153
-
154
- ```javascript
155
- {
156
- "firstName": "Harry",
157
- "lastName": "Houdini",
158
- "career": "magician"
159
- }
160
- ```
161
-
162
- Note that the `admin` is now not included in the payload.
163
-
164
- Setting `serialize` to `true` enforces serialization for hasMany
165
- relationships even if it's neither a many-to-many nor many-to-none
166
- relationship.
167
-
168
- @property attrs
169
- @public
170
- @type {Object}
171
- */
172
- mergedProperties: Object;
173
- /**
174
- Given a subclass of `Model` and a JSON object this method will
175
- iterate through each attribute of the `Model` and invoke the
176
- `Transform#deserialize` method on the matching property of the
177
- JSON object. This method is typically called after the
178
- serializer's `normalize` method.
179
-
180
- @method applyTransforms
181
- @private
182
- @param {Model} typeClass
183
- @param {Object} data The data to transform
184
- @return {Object} data The transformed data object
185
- */
186
- applyTransforms(typeClass: Model, data: Object): Object;
187
- /**
188
- The `normalizeResponse` method is used to normalize a payload from the
189
- server to a JSON-API Document.
190
-
191
- http://jsonapi.org/format/#document-structure
192
-
193
- This method delegates to a more specific normalize method based on
194
- the `requestType`.
195
-
196
- To override this method with a custom one, make sure to call
197
- `return super.normalizeResponse(store, primaryModelClass, payload, id, requestType)` with your
198
- pre-processed data.
199
-
200
- Here's an example of using `normalizeResponse` manually:
201
-
202
- ```javascript
203
- socket.on('message', function(message) {
204
- let data = message.data;
205
- let modelClass = store.modelFor(data.modelName);
206
- let serializer = store.serializerFor(data.modelName);
207
- let normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id);
208
-
209
- store.push(normalized);
210
- });
211
- ```
212
-
213
- @since 1.13.0
214
- @method normalizeResponse
215
- @public
216
- @param {Store} store
217
- @param {Model} primaryModelClass
218
- @param {Object} payload
219
- @param {String|Number} id
220
- @param {String} requestType
221
- @return {Object} JSON-API Document
222
- */
223
- normalizeResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
224
- /**
225
- Called by the default normalizeResponse implementation when the
226
- type of request is `findRecord`
227
-
228
- @since 1.13.0
229
- @method normalizeFindRecordResponse
230
- @public
231
- @param {Store} store
232
- @param {Model} primaryModelClass
233
- @param {Object} payload
234
- @param {String|Number} id
235
- @param {String} requestType
236
- @return {Object} JSON-API Document
237
- */
238
- normalizeFindRecordResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
239
- /**
240
- Called by the default normalizeResponse implementation when the
241
- type of request is `queryRecord`
242
-
243
- @since 1.13.0
244
- @method normalizeQueryRecordResponse
245
- @public
246
- @param {Store} store
247
- @param {Model} primaryModelClass
248
- @param {Object} payload
249
- @param {String|Number} id
250
- @param {String} requestType
251
- @return {Object} JSON-API Document
252
- */
253
- normalizeQueryRecordResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
254
- /**
255
- Called by the default normalizeResponse implementation when the
256
- type of request is `findAll`
257
-
258
- @since 1.13.0
259
- @method normalizeFindAllResponse
260
- @public
261
- @param {Store} store
262
- @param {Model} primaryModelClass
263
- @param {Object} payload
264
- @param {String|Number} id
265
- @param {String} requestType
266
- @return {Object} JSON-API Document
267
- */
268
- normalizeFindAllResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
269
- /**
270
- Called by the default normalizeResponse implementation when the
271
- type of request is `findBelongsTo`
272
-
273
- @since 1.13.0
274
- @method normalizeFindBelongsToResponse
275
- @public
276
- @param {Store} store
277
- @param {Model} primaryModelClass
278
- @param {Object} payload
279
- @param {String|Number} id
280
- @param {String} requestType
281
- @return {Object} JSON-API Document
282
- */
283
- normalizeFindBelongsToResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
284
- /**
285
- Called by the default normalizeResponse implementation when the
286
- type of request is `findHasMany`
287
-
288
- @since 1.13.0
289
- @method normalizeFindHasManyResponse
290
- @public
291
- @param {Store} store
292
- @param {Model} primaryModelClass
293
- @param {Object} payload
294
- @param {String|Number} id
295
- @param {String} requestType
296
- @return {Object} JSON-API Document
297
- */
298
- normalizeFindHasManyResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
299
- /**
300
- Called by the default normalizeResponse implementation when the
301
- type of request is `findMany`
302
-
303
- @since 1.13.0
304
- @method normalizeFindManyResponse
305
- @public
306
- @param {Store} store
307
- @param {Model} primaryModelClass
308
- @param {Object} payload
309
- @param {String|Number} id
310
- @param {String} requestType
311
- @return {Object} JSON-API Document
312
- */
313
- normalizeFindManyResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
314
- /**
315
- Called by the default normalizeResponse implementation when the
316
- type of request is `query`
317
-
318
- @since 1.13.0
319
- @method normalizeQueryResponse
320
- @public
321
- @param {Store} store
322
- @param {Model} primaryModelClass
323
- @param {Object} payload
324
- @param {String|Number} id
325
- @param {String} requestType
326
- @return {Object} JSON-API Document
327
- */
328
- normalizeQueryResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
329
- /**
330
- Called by the default normalizeResponse implementation when the
331
- type of request is `createRecord`
332
-
333
- @since 1.13.0
334
- @method normalizeCreateRecordResponse
335
- @public
336
- @param {Store} store
337
- @param {Model} primaryModelClass
338
- @param {Object} payload
339
- @param {String|Number} id
340
- @param {String} requestType
341
- @return {Object} JSON-API Document
342
- */
343
- normalizeCreateRecordResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
344
- /**
345
- Called by the default normalizeResponse implementation when the
346
- type of request is `deleteRecord`
347
-
348
- @since 1.13.0
349
- @method normalizeDeleteRecordResponse
350
- @public
351
- @param {Store} store
352
- @param {Model} primaryModelClass
353
- @param {Object} payload
354
- @param {String|Number} id
355
- @param {String} requestType
356
- @return {Object} JSON-API Document
357
- */
358
- normalizeDeleteRecordResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
359
- /**
360
- Called by the default normalizeResponse implementation when the
361
- type of request is `updateRecord`
362
-
363
- @since 1.13.0
364
- @method normalizeUpdateRecordResponse
365
- @public
366
- @param {Store} store
367
- @param {Model} primaryModelClass
368
- @param {Object} payload
369
- @param {String|Number} id
370
- @param {String} requestType
371
- @return {Object} JSON-API Document
372
- */
373
- normalizeUpdateRecordResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
374
- /**
375
- normalizeUpdateRecordResponse, normalizeCreateRecordResponse and
376
- normalizeDeleteRecordResponse delegate to this method by default.
377
-
378
- @since 1.13.0
379
- @method normalizeSaveResponse
380
- @public
381
- @param {Store} store
382
- @param {Model} primaryModelClass
383
- @param {Object} payload
384
- @param {String|Number} id
385
- @param {String} requestType
386
- @return {Object} JSON-API Document
387
- */
388
- normalizeSaveResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, ...args: any[]): Object;
389
- /**
390
- normalizeQueryResponse and normalizeFindRecordResponse delegate to this
391
- method by default.
392
-
393
- @since 1.13.0
394
- @method normalizeSingleResponse
395
- @public
396
- @param {Store} store
397
- @param {Model} primaryModelClass
398
- @param {Object} payload
399
- @param {String|Number} id
400
- @param {String} requestType
401
- @return {Object} JSON-API Document
402
- */
403
- normalizeSingleResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string): Object;
404
- /**
405
- normalizeQueryResponse, normalizeFindManyResponse, and normalizeFindHasManyResponse delegate
406
- to this method by default.
407
-
408
- @since 1.13.0
409
- @method normalizeArrayResponse
410
- @public
411
- @param {Store} store
412
- @param {Model} primaryModelClass
413
- @param {Object} payload
414
- @param {String|Number} id
415
- @param {String} requestType
416
- @return {Object} JSON-API Document
417
- */
418
- normalizeArrayResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string): Object;
419
- /**
420
- @method _normalizeResponse
421
- @param {Store} store
422
- @param {Model} primaryModelClass
423
- @param {Object} payload
424
- @param {String|Number} id
425
- @param {String} requestType
426
- @param {Boolean} isSingle
427
- @return {Object} JSON-API Document
428
- @private
429
- */
430
- _normalizeResponse(store: Store, primaryModelClass: Model, payload: Object, id: string | number, requestType: string, isSingle: boolean): Object;
431
- /**
432
- Normalizes a part of the JSON payload returned by
433
- the server. You should override this method, munge the hash
434
- and call super if you have generic normalization to do.
435
-
436
- It takes the type of the record that is being normalized
437
- (as a Model class), the property where the hash was
438
- originally found, and the hash to normalize.
439
-
440
- You can use this method, for example, to normalize underscored keys to camelized
441
- or other general-purpose normalizations.
442
-
443
- Example
444
-
445
- ```app/serializers/application.js
446
- import JSONSerializer from '@ember-data-mirror/serializer/json';
447
- import { underscore } from '<app-name>/utils/string-utils';
448
- import { get } from '@ember/object';
449
-
450
- export default class ApplicationSerializer extends JSONSerializer {
451
- normalize(typeClass, hash) {
452
- let fields = typeClass.fields;
453
-
454
- fields.forEach(function(type, field) {
455
- let payloadField = underscore(field);
456
- if (field === payloadField) { return; }
457
-
458
- hash[field] = hash[payloadField];
459
- delete hash[payloadField];
460
- });
461
-
462
- return super.normalize(...arguments);
463
- }
464
- }
465
- ```
466
-
467
- @method normalize
468
- @public
469
- @param {Model} typeClass
470
- @param {Object} hash
471
- @return {Object}
472
- */
473
- normalize(modelClass: any, resourceHash: any): Object;
474
- /**
475
- Returns the resource's ID.
476
-
477
- @method extractId
478
- @public
479
- @param {Object} modelClass
480
- @param {Object} resourceHash
481
- @return {String}
482
- */
483
- extractId(modelClass: Object, resourceHash: Object): string;
484
- /**
485
- Returns the resource's attributes formatted as a JSON-API "attributes object".
486
-
487
- http://jsonapi.org/format/#document-resource-object-attributes
488
-
489
- @method extractAttributes
490
- @public
491
- @param {Object} modelClass
492
- @param {Object} resourceHash
493
- @return {Object}
494
- */
495
- extractAttributes(modelClass: Object, resourceHash: Object): Object;
496
- /**
497
- Returns a relationship formatted as a JSON-API "relationship object".
498
-
499
- http://jsonapi.org/format/#document-resource-object-relationships
500
-
501
- @method extractRelationship
502
- @public
503
- @param {Object} relationshipModelName
504
- @param {Object} relationshipHash
505
- @return {Object}
506
- */
507
- extractRelationship(relationshipModelName: Object, relationshipHash: Object): Object;
508
- /**
509
- Returns a polymorphic relationship formatted as a JSON-API "relationship object".
510
-
511
- http://jsonapi.org/format/#document-resource-object-relationships
512
-
513
- `relationshipOptions` is a hash which contains more information about the
514
- polymorphic relationship which should be extracted:
515
- - `resourceHash` complete hash of the resource the relationship should be
516
- extracted from
517
- - `relationshipKey` key under which the value for the relationship is
518
- extracted from the resourceHash
519
- - `relationshipMeta` meta information about the relationship
520
-
521
- @method extractPolymorphicRelationship
522
- @public
523
- @param {Object} relationshipModelName
524
- @param {Object} relationshipHash
525
- @param {Object} relationshipOptions
526
- @return {Object}
527
- */
528
- extractPolymorphicRelationship(relationshipModelName: Object, relationshipHash: Object, relationshipOptions: Object): Object;
529
- /**
530
- Returns the resource's relationships formatted as a JSON-API "relationships object".
531
-
532
- http://jsonapi.org/format/#document-resource-object-relationships
533
-
534
- @method extractRelationships
535
- @public
536
- @param {Object} modelClass
537
- @param {Object} resourceHash
538
- @return {Object}
539
- */
540
- extractRelationships(modelClass: Object, resourceHash: Object): Object;
541
- /**
542
- Dasherizes the model name in the payload
543
-
544
- @method modelNameFromPayloadKey
545
- @public
546
- @param {String} key
547
- @return {String} the model's modelName
548
- */
549
- modelNameFromPayloadKey(key: string): string;
550
- /**
551
- @method normalizeRelationships
552
- @private
553
- */
554
- normalizeRelationships(typeClass: any, hash: any): void;
555
- /**
556
- @method normalizeUsingDeclaredMapping
557
- @private
558
- */
559
- normalizeUsingDeclaredMapping(modelClass: any, hash: any): void;
560
- /**
561
- Looks up the property key that was set by the custom `attr` mapping
562
- passed to the serializer.
563
-
564
- @method _getMappedKey
565
- @private
566
- @param {String} key
567
- @return {String} key
568
- */
569
- _getMappedKey(key: string, modelClass: any): string;
570
- /**
571
- Check attrs.key.serialize property to inform if the `key`
572
- can be serialized
573
-
574
- @method _canSerialize
575
- @private
576
- @param {String} key
577
- @return {Boolean} true if the key can be serialized
578
- */
579
- _canSerialize(key: string): boolean;
580
- /**
581
- When attrs.key.serialize is set to true then
582
- it takes priority over the other checks and the related
583
- attribute/relationship will be serialized
584
-
585
- @method _mustSerialize
586
- @private
587
- @param {String} key
588
- @return {Boolean} true if the key must be serialized
589
- */
590
- _mustSerialize(key: string): boolean;
591
- /**
592
- Check if the given hasMany relationship should be serialized
593
-
594
- By default only many-to-many and many-to-none relationships are serialized.
595
- This could be configured per relationship by Serializer's `attrs` object.
596
-
597
- @method shouldSerializeHasMany
598
- @public
599
- @param {Snapshot} snapshot
600
- @param {String} key
601
- @param {RelationshipSchema} relationship
602
- @return {Boolean} true if the hasMany relationship should be serialized
603
- */
604
- shouldSerializeHasMany(snapshot: Snapshot, key: string, relationship: RelationshipSchema): boolean;
605
- /**
606
- Called when a record is saved in order to convert the
607
- record into JSON.
608
-
609
- By default, it creates a JSON object with a key for
610
- each attribute and belongsTo relationship.
611
-
612
- For example, consider this model:
613
-
614
- ```app/models/comment.js
615
- import Model, { attr, belongsTo } from '@ember-data-mirror/model';
616
-
617
- export default class CommentModel extends Model {
618
- @attr title;
619
- @attr body;
620
-
621
- @belongsTo('user') author;
622
- }
623
- ```
624
-
625
- The default serialization would create a JSON object like:
626
-
627
- ```javascript
628
- {
629
- "title": "Rails is unagi",
630
- "body": "Rails? Omakase? O_O",
631
- "author": 12
632
- }
633
- ```
634
-
635
- By default, attributes are passed through as-is, unless
636
- you specified an attribute type (`attr('date')`). If
637
- you specify a transform, the JavaScript value will be
638
- serialized when inserted into the JSON hash.
639
-
640
- By default, belongs-to relationships are converted into
641
- IDs when inserted into the JSON hash.
642
-
643
- ## IDs
644
-
645
- `serialize` takes an options hash with a single option:
646
- `includeId`. If this option is `true`, `serialize` will,
647
- by default include the ID in the JSON object it builds.
648
-
649
- The adapter passes in `includeId: true` when serializing
650
- a record for `createRecord`, but not for `updateRecord`.
651
-
652
- ## Customization
653
-
654
- Your server may expect a different JSON format than the
655
- built-in serialization format.
656
-
657
- In that case, you can implement `serialize` yourself and
658
- return a JSON hash of your choosing.
659
-
660
- ```app/serializers/post.js
661
- import JSONSerializer from '@ember-data-mirror/serializer/json';
662
-
663
- export default class PostSerializer extends JSONSerializer {
664
- serialize(snapshot, options) {
665
- let json = {
666
- POST_TTL: snapshot.attr('title'),
667
- POST_BDY: snapshot.attr('body'),
668
- POST_CMS: snapshot.hasMany('comments', { ids: true })
669
- };
670
-
671
- if (options.includeId) {
672
- json.POST_ID_ = snapshot.id;
673
- }
674
-
675
- return json;
676
- }
677
- }
678
- ```
679
-
680
- ## Customizing an App-Wide Serializer
681
-
682
- If you want to define a serializer for your entire
683
- application, you'll probably want to use `eachAttribute`
684
- and `eachRelationship` on the record.
685
-
686
- ```app/serializers/application.js
687
- import JSONSerializer from '@ember-data-mirror/serializer/json';
688
- import { singularize } from '<app-name>/utils/string-utils';
689
-
690
- export default class ApplicationSerializer extends JSONSerializer {
691
- serialize(snapshot, options) {
692
- let json = {};
693
-
694
- snapshot.eachAttribute((name) => {
695
- json[serverAttributeName(name)] = snapshot.attr(name);
696
- });
697
-
698
- snapshot.eachRelationship((name, relationship) => {
699
- if (relationship.kind === 'hasMany') {
700
- json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
701
- }
702
- });
703
-
704
- if (options.includeId) {
705
- json.ID_ = snapshot.id;
706
- }
707
-
708
- return json;
709
- }
710
- }
711
-
712
- function serverAttributeName(attribute) {
713
- return attribute.underscore().toUpperCase();
714
- }
715
-
716
- function serverHasManyName(name) {
717
- return serverAttributeName(singularize(name)) + "_IDS";
718
- }
719
- ```
720
-
721
- This serializer will generate JSON that looks like this:
722
-
723
- ```javascript
724
- {
725
- "TITLE": "Rails is omakase",
726
- "BODY": "Yep. Omakase.",
727
- "COMMENT_IDS": [ "1", "2", "3" ]
728
- }
729
- ```
730
-
731
- ## Tweaking the Default JSON
732
-
733
- If you just want to do some small tweaks on the default JSON,
734
- you can call `super.serialize` first and make the tweaks on
735
- the returned JSON.
736
-
737
- ```app/serializers/post.js
738
- import JSONSerializer from '@ember-data-mirror/serializer/json';
739
-
740
- export default class PostSerializer extends JSONSerializer {
741
- serialize(snapshot, options) {
742
- let json = super.serialize(...arguments);
743
-
744
- json.subject = json.title;
745
- delete json.title;
746
-
747
- return json;
748
- }
749
- }
750
- ```
751
-
752
- @method serialize
753
- @public
754
- @param {Snapshot} snapshot
755
- @param {Object} options
756
- @return {Object} json
757
- */
758
- serialize(snapshot: Snapshot, options: Object): Object;
759
- /**
760
- You can use this method to customize how a serialized record is added to the complete
761
- JSON hash to be sent to the server. By default the JSON Serializer does not namespace
762
- the payload and just sends the raw serialized JSON object.
763
- If your server expects namespaced keys, you should consider using the RESTSerializer.
764
- Otherwise you can override this method to customize how the record is added to the hash.
765
- The hash property should be modified by reference.
766
-
767
- For example, your server may expect underscored root objects.
768
-
769
- ```app/serializers/application.js
770
- import RESTSerializer from '@ember-data-mirror/serializer/rest';
771
- import { underscoren} from '<app-name>/utils/string-utils';
772
-
773
- export default class ApplicationSerializer extends RESTSerializer {
774
- serializeIntoHash(data, type, snapshot, options) {
775
- let root = underscore(type.modelName);
776
- data[root] = this.serialize(snapshot, options);
777
- }
778
- }
779
- ```
780
-
781
- @method serializeIntoHash
782
- @public
783
- @param {Object} hash
784
- @param {Model} typeClass
785
- @param {Snapshot} snapshot
786
- @param {Object} options
787
- */
788
- serializeIntoHash(hash: Object, typeClass: Model, snapshot: Snapshot, options: Object): void;
789
- /**
790
- `serializeAttribute` can be used to customize how `attr`
791
- properties are serialized
792
-
793
- For example if you wanted to ensure all your attributes were always
794
- serialized as properties on an `attributes` object you could
795
- write:
796
-
797
- ```app/serializers/application.js
798
- import JSONSerializer from '@ember-data-mirror/serializer/json';
799
-
800
- export default class ApplicationSerializer extends JSONSerializer {
801
- serializeAttribute(snapshot, json, key, attributes) {
802
- json.attributes = json.attributes || {};
803
- super.serializeAttribute(snapshot, json.attributes, key, attributes);
804
- }
805
- }
806
- ```
807
-
808
- @method serializeAttribute
809
- @public
810
- @param {Snapshot} snapshot
811
- @param {Object} json
812
- @param {String} key
813
- @param {Object} attribute
814
- */
815
- serializeAttribute(snapshot: Snapshot, json: Object, key: string, attribute: Object): void;
816
- /**
817
- `serializeBelongsTo` can be used to customize how `belongsTo`
818
- properties are serialized.
819
-
820
- Example
821
-
822
- ```app/serializers/post.js
823
- import JSONSerializer from '@ember-data-mirror/serializer/json';
824
-
825
- export default class PostSerializer extends JSONSerializer {
826
- serializeBelongsTo(snapshot, json, relationship) {
827
- let key = relationship.name;
828
- let belongsTo = snapshot.belongsTo(key);
829
-
830
- key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key;
831
-
832
- json[key] = !belongsTo ? null : belongsTo.record.toJSON();
833
- }
834
- }
835
- ```
836
-
837
- @method serializeBelongsTo
838
- @public
839
- @param {Snapshot} snapshot
840
- @param {Object} json
841
- @param {Object} relationship
842
- */
843
- serializeBelongsTo(snapshot: Snapshot, json: Object, relationship: Object): void;
844
- /**
845
- `serializeHasMany` can be used to customize how `hasMany`
846
- properties are serialized.
847
-
848
- Example
849
-
850
- ```app/serializers/post.js
851
- import JSONSerializer from '@ember-data-mirror/serializer/json';
852
-
853
- export default class PostSerializer extends JSONSerializer {
854
- serializeHasMany(snapshot, json, relationship) {
855
- let key = relationship.name;
856
- if (key === 'comments') {
857
- return;
858
- } else {
859
- super.serializeHasMany(...arguments);
860
- }
861
- }
862
- }
863
- ```
864
-
865
- @method serializeHasMany
866
- @public
867
- @param {Snapshot} snapshot
868
- @param {Object} json
869
- @param {Object} relationship
870
- */
871
- serializeHasMany(snapshot: Snapshot, json: Object, relationship: Object): void;
872
- /**
873
- You can use this method to customize how polymorphic objects are
874
- serialized. Objects are considered to be polymorphic if
875
- `{ polymorphic: true }` is pass as the second argument to the
876
- `belongsTo` function.
877
-
878
- Example
879
-
880
- ```app/serializers/comment.js
881
- import JSONSerializer from '@ember-data-mirror/serializer/json';
882
-
883
- export default class CommentSerializer extends JSONSerializer {
884
- serializePolymorphicType(snapshot, json, relationship) {
885
- let key = relationship.name;
886
- let belongsTo = snapshot.belongsTo(key);
887
-
888
- key = this.keyForAttribute ? this.keyForAttribute(key, 'serialize') : key;
889
-
890
- if (!belongsTo) {
891
- json[key + '_type'] = null;
892
- } else {
893
- json[key + '_type'] = belongsTo.modelName;
894
- }
895
- }
896
- }
897
- ```
898
-
899
- @method serializePolymorphicType
900
- @public
901
- @param {Snapshot} snapshot
902
- @param {Object} json
903
- @param {Object} relationship
904
- */
905
- serializePolymorphicType(): void;
906
- /**
907
- `extractMeta` is used to deserialize any meta information in the
908
- adapter payload. By default Ember Data expects meta information to
909
- be located on the `meta` property of the payload object.
910
-
911
- Example
912
-
913
- ```app/serializers/post.js
914
- import JSONSerializer from '@ember-data-mirror/serializer/json';
915
-
916
- export default class PostSerializer extends JSONSerializer {
917
- extractMeta(store, typeClass, payload) {
918
- if (payload && payload.hasOwnProperty('_pagination')) {
919
- let meta = payload._pagination;
920
- delete payload._pagination;
921
- return meta;
922
- }
923
- }
924
- }
925
- ```
926
-
927
- @method extractMeta
928
- @public
929
- @param {Store} store
930
- @param {Model} modelClass
931
- @param {Object} payload
932
- */
933
- extractMeta(store: Store, modelClass: Model, payload: Object): any;
934
- /**
935
- `extractErrors` is used to extract model errors when a call
936
- to `Model#save` fails with an `InvalidError`. By default
937
- Ember Data expects error information to be located on the `errors`
938
- property of the payload object.
939
-
940
- This serializer expects this `errors` object to be an Array similar
941
- to the following, compliant with the https://jsonapi.org/format/#errors specification:
942
-
943
- ```js
944
- {
945
- "errors": [
946
- {
947
- "detail": "This username is already taken!",
948
- "source": {
949
- "pointer": "data/attributes/username"
950
- }
951
- }, {
952
- "detail": "Doesn't look like a valid email.",
953
- "source": {
954
- "pointer": "data/attributes/email"
955
- }
956
- }
957
- ]
958
- }
959
- ```
960
-
961
- The key `detail` provides a textual description of the problem.
962
- Alternatively, the key `title` can be used for the same purpose.
963
-
964
- The nested keys `source.pointer` detail which specific element
965
- of the request data was invalid.
966
-
967
- Note that JSON-API also allows for object-level errors to be placed
968
- in an object with pointer `data`, signifying that the problem
969
- cannot be traced to a specific attribute:
970
-
971
- ```javascript
972
- {
973
- "errors": [
974
- {
975
- "detail": "Some generic non property error message",
976
- "source": {
977
- "pointer": "data"
978
- }
979
- }
980
- ]
981
- }
982
- ```
983
-
984
- When turn into a `Errors` object, you can read these errors
985
- through the property `base`:
986
-
987
- ```handlebars
988
- {{#each @model.errors.base as |error|}}
989
- <div class="error">
990
- {{error.message}}
991
- </div>
992
- {{/each}}
993
- ```
994
-
995
- Example of alternative implementation, overriding the default
996
- behavior to deal with a different format of errors:
997
-
998
- ```app/serializers/post.js
999
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1000
-
1001
- export default class PostSerializer extends JSONSerializer {
1002
- extractErrors(store, typeClass, payload, id) {
1003
- if (payload && typeof payload === 'object' && payload._problems) {
1004
- payload = payload._problems;
1005
- this.normalizeErrors(typeClass, payload);
1006
- }
1007
- return payload;
1008
- }
1009
- }
1010
- ```
1011
-
1012
- @method extractErrors
1013
- @public
1014
- @param {Store} store
1015
- @param {Model} typeClass
1016
- @param {Object} payload
1017
- @param {(String|Number)} id
1018
- @return {Object} json The deserialized errors
1019
- */
1020
- extractErrors(store: Store, typeClass: Model, payload: Object, id: (string | number)): Object;
1021
- /**
1022
- `keyForAttribute` can be used to define rules for how to convert an
1023
- attribute name in your model to a key in your JSON.
1024
-
1025
- Example
1026
-
1027
- ```app/serializers/application.js
1028
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1029
- import { underscore } from '<app-name>/utils/string-utils';
1030
-
1031
- export default class ApplicationSerializer extends JSONSerializer {
1032
- keyForAttribute(attr, method) {
1033
- return underscore(attr).toUpperCase();
1034
- }
1035
- }
1036
- ```
1037
-
1038
- @method keyForAttribute
1039
- @public
1040
- @param {String} key
1041
- @param {String} method
1042
- @return {String} normalized key
1043
- */
1044
- keyForAttribute(key: string, method: string): string;
1045
- /**
1046
- `keyForRelationship` can be used to define a custom key when
1047
- serializing and deserializing relationship properties. By default
1048
- `JSONSerializer` does not provide an implementation of this method.
1049
-
1050
- Example
1051
-
1052
- ```app/serializers/post.js
1053
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1054
- import { underscore } from '<app-name>/utils/string-utils';
1055
-
1056
- export default class PostSerializer extends JSONSerializer {
1057
- keyForRelationship(key, relationship, method) {
1058
- return `rel_${underscore(key)}`;
1059
- }
1060
- }
1061
- ```
1062
-
1063
- @method keyForRelationship
1064
- @public
1065
- @param {String} key
1066
- @param {String} typeClass
1067
- @param {String} method
1068
- @return {String} normalized key
1069
- */
1070
- keyForRelationship(key: string, typeClass: string, method: string): string;
1071
- /**
1072
- `keyForLink` can be used to define a custom key when deserializing link
1073
- properties.
1074
-
1075
- @method keyForLink
1076
- @public
1077
- @param {String} key
1078
- @param {String} kind `belongsTo` or `hasMany`
1079
- @return {String} normalized key
1080
- */
1081
- keyForLink(key: string, kind: string): string;
1082
- /**
1083
- @method transformFor
1084
- @private
1085
- @param {String} attributeType
1086
- @param {Boolean} skipAssertion
1087
- @return {Transform} transform
1088
- */
1089
- transformFor(attributeType: string, skipAssertion: boolean): Transform;
1090
- };
1091
- import Serializer from '@ember-data-mirror/serializer';
1092
- }
1093
- //# sourceMappingURL=json.d.ts.map
4
+ }