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