@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,1396 +0,0 @@
1
- import { getOwner } from '@ember/application';
2
- import { warn } from '@ember/debug';
3
- import { dasherize, singularize } from '@ember-data-mirror/request-utils/string';
4
- import Serializer from "./index.js";
5
- import { macroCondition, getGlobalConfig } from '@embroider/macros';
6
- function coerceId(id) {
7
- if (id === null || id === undefined || id === '') {
8
- return null;
9
- } else if (typeof id === 'string') {
10
- return id;
11
- } else if (typeof id === 'symbol') {
12
- return id.toString();
13
- } else {
14
- return String(id);
15
- }
16
- }
17
-
18
- /**
19
- * @module @ember-data-mirror/serializer/json
20
- */
21
- const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
22
- const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
23
- const PRIMARY_ATTRIBUTE_KEY = 'base';
24
-
25
- /**
26
- * <blockquote style="margin: 1em; padding: .1em 1em .1em 1em; border-left: solid 1em #E34C32; background: #e0e0e0;">
27
- <p>
28
- ⚠️ <strong>This is LEGACY documentation</strong> for a feature that is no longer encouraged to be used.
29
- If starting a new app or thinking of implementing a new adapter, consider writing a
30
- <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>
31
- </p>
32
- </blockquote>
33
-
34
- In EmberData a Serializer is used to serialize and deserialize
35
- records when they are transferred in and out of an external source.
36
- This process involves normalizing property names, transforming
37
- attribute values and serializing relationships.
38
-
39
- By default, EmberData uses and recommends the `JSONAPISerializer`.
40
-
41
- `JSONSerializer` is useful for simpler or legacy backends that may
42
- not support the http://jsonapi.org/ spec.
43
-
44
- For example, given the following `User` model and JSON payload:
45
-
46
- ```app/models/user.js
47
- import Model, { attr, belongsTo, hasMany } from '@ember-data-mirror/model';
48
-
49
- export default class UserModel extends Model {
50
- @hasMany('user') friends;
51
- @belongsTo('location') house;
52
-
53
- @attr('string') name;
54
- }
55
- ```
56
-
57
- ```js
58
- {
59
- id: 1,
60
- name: 'Sebastian',
61
- friends: [3, 4],
62
- links: {
63
- house: '/houses/lefkada'
64
- }
65
- }
66
- ```
67
-
68
- `JSONSerializer` will normalize the JSON payload to the JSON API format that the
69
- Ember Data store expects.
70
-
71
- You can customize how JSONSerializer processes its payload by passing options in
72
- the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks:
73
-
74
- - To customize how a single record is normalized, use the `normalize` hook.
75
- - To customize how `JSONSerializer` normalizes the whole server response, use the
76
- `normalizeResponse` hook.
77
- - To customize how `JSONSerializer` normalizes a specific response from the server,
78
- use one of the many specific `normalizeResponse` hooks.
79
- - To customize how `JSONSerializer` normalizes your id, attributes or relationships,
80
- use the `extractId`, `extractAttributes` and `extractRelationships` hooks.
81
-
82
- The `JSONSerializer` normalization process follows these steps:
83
-
84
- 1. `normalizeResponse`
85
- - entry method to the serializer.
86
- 2. `normalizeCreateRecordResponse`
87
- - a `normalizeResponse` for a specific operation is called.
88
- 3. `normalizeSingleResponse`|`normalizeArrayResponse`
89
- - for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple records back.
90
- 4. `normalize`
91
- - `normalizeArrayResponse` iterates and calls `normalize` for each of its records while `normalizeSingle`
92
- calls it once. This is the method you most likely want to subclass.
93
- 5. `extractId` | `extractAttributes` | `extractRelationships`
94
- - `normalize` delegates to these methods to
95
- turn the record payload into the JSON API format.
96
-
97
- @main @ember-data-mirror/serializer/json
98
- @class JSONSerializer
99
- @public
100
- @extends Serializer
101
- */
102
- const JSONSerializer = Serializer.extend({
103
- /**
104
- The `primaryKey` is used when serializing and deserializing
105
- data. Ember Data always uses the `id` property to store the id of
106
- the record. The external source may not always follow this
107
- convention. In these cases it is useful to override the
108
- `primaryKey` property to match the `primaryKey` of your external
109
- store.
110
- Example
111
- ```app/serializers/application.js
112
- import JSONSerializer from '@ember-data-mirror/serializer/json';
113
- export default class ApplicationSerializer extends JSONSerializer {
114
- primaryKey = '_id'
115
- }
116
- ```
117
- @property primaryKey
118
- @type {String}
119
- @public
120
- @default 'id'
121
- */
122
- primaryKey: 'id',
123
- /**
124
- The `attrs` object can be used to declare a simple mapping between
125
- property names on `Model` records and payload keys in the
126
- serialized JSON object representing the record. An object with the
127
- property `key` can also be used to designate the attribute's key on
128
- the response payload.
129
- Example
130
- ```app/models/person.js
131
- import Model, { attr } from '@ember-data-mirror/model';
132
- export default class PersonModel extends Model {
133
- @attr('string') firstName;
134
- @attr('string') lastName;
135
- @attr('string') occupation;
136
- @attr('boolean') admin;
137
- }
138
- ```
139
- ```app/serializers/person.js
140
- import JSONSerializer from '@ember-data-mirror/serializer/json';
141
- export default class PersonSerializer extends JSONSerializer {
142
- attrs = {
143
- admin: 'is_admin',
144
- occupation: { key: 'career' }
145
- }
146
- }
147
- ```
148
- You can also remove attributes and relationships by setting the `serialize`
149
- key to `false` in your mapping object.
150
- Example
151
- ```app/serializers/person.js
152
- import JSONSerializer from '@ember-data-mirror/serializer/json';
153
- export default class PostSerializer extends JSONSerializer {
154
- attrs = {
155
- admin: { serialize: false },
156
- occupation: { key: 'career' }
157
- }
158
- }
159
- ```
160
- When serialized:
161
- ```javascript
162
- {
163
- "firstName": "Harry",
164
- "lastName": "Houdini",
165
- "career": "magician"
166
- }
167
- ```
168
- Note that the `admin` is now not included in the payload.
169
- Setting `serialize` to `true` enforces serialization for hasMany
170
- relationships even if it's neither a many-to-many nor many-to-none
171
- relationship.
172
- @property attrs
173
- @public
174
- @type {Object}
175
- */
176
- mergedProperties: ['attrs'],
177
- /**
178
- Given a subclass of `Model` and a JSON object this method will
179
- iterate through each attribute of the `Model` and invoke the
180
- `Transform#deserialize` method on the matching property of the
181
- JSON object. This method is typically called after the
182
- serializer's `normalize` method.
183
- @method applyTransforms
184
- @private
185
- @param {Model} typeClass
186
- @param {Object} data The data to transform
187
- @return {Object} data The transformed data object
188
- */
189
- applyTransforms(typeClass, data) {
190
- const attributes = typeClass.attributes;
191
- typeClass.eachTransformedAttribute((key, typeClass) => {
192
- if (data[key] === undefined) {
193
- return;
194
- }
195
- const transform = this.transformFor(typeClass);
196
- const transformMeta = attributes.get(key);
197
- data[key] = transform.deserialize(data[key], transformMeta.options);
198
- });
199
- return data;
200
- },
201
- /**
202
- The `normalizeResponse` method is used to normalize a payload from the
203
- server to a JSON-API Document.
204
- http://jsonapi.org/format/#document-structure
205
- This method delegates to a more specific normalize method based on
206
- the `requestType`.
207
- To override this method with a custom one, make sure to call
208
- `return super.normalizeResponse(store, primaryModelClass, payload, id, requestType)` with your
209
- pre-processed data.
210
- Here's an example of using `normalizeResponse` manually:
211
- ```javascript
212
- socket.on('message', function(message) {
213
- let data = message.data;
214
- let modelClass = store.modelFor(data.modelName);
215
- let serializer = store.serializerFor(data.modelName);
216
- let normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id);
217
- store.push(normalized);
218
- });
219
- ```
220
- @since 1.13.0
221
- @method normalizeResponse
222
- @public
223
- @param {Store} store
224
- @param {Model} primaryModelClass
225
- @param {Object} payload
226
- @param {String|Number} id
227
- @param {String} requestType
228
- @return {Object} JSON-API Document
229
- */
230
- normalizeResponse(store, primaryModelClass, payload, id, requestType) {
231
- switch (requestType) {
232
- case 'findRecord':
233
- return this.normalizeFindRecordResponse(...arguments);
234
- case 'queryRecord':
235
- return this.normalizeQueryRecordResponse(...arguments);
236
- case 'findAll':
237
- return this.normalizeFindAllResponse(...arguments);
238
- case 'findBelongsTo':
239
- return this.normalizeFindBelongsToResponse(...arguments);
240
- case 'findHasMany':
241
- return this.normalizeFindHasManyResponse(...arguments);
242
- case 'findMany':
243
- return this.normalizeFindManyResponse(...arguments);
244
- case 'query':
245
- return this.normalizeQueryResponse(...arguments);
246
- case 'createRecord':
247
- return this.normalizeCreateRecordResponse(...arguments);
248
- case 'deleteRecord':
249
- return this.normalizeDeleteRecordResponse(...arguments);
250
- case 'updateRecord':
251
- return this.normalizeUpdateRecordResponse(...arguments);
252
- }
253
- },
254
- /**
255
- Called by the default normalizeResponse implementation when the
256
- type of request is `findRecord`
257
- @since 1.13.0
258
- @method normalizeFindRecordResponse
259
- @public
260
- @param {Store} store
261
- @param {Model} primaryModelClass
262
- @param {Object} payload
263
- @param {String|Number} id
264
- @param {String} requestType
265
- @return {Object} JSON-API Document
266
- */
267
- normalizeFindRecordResponse(store, primaryModelClass, payload, id, requestType) {
268
- return this.normalizeSingleResponse(...arguments);
269
- },
270
- /**
271
- Called by the default normalizeResponse implementation when the
272
- type of request is `queryRecord`
273
- @since 1.13.0
274
- @method normalizeQueryRecordResponse
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
- normalizeQueryRecordResponse(store, primaryModelClass, payload, id, requestType) {
284
- return this.normalizeSingleResponse(...arguments);
285
- },
286
- /**
287
- Called by the default normalizeResponse implementation when the
288
- type of request is `findAll`
289
- @since 1.13.0
290
- @method normalizeFindAllResponse
291
- @public
292
- @param {Store} store
293
- @param {Model} primaryModelClass
294
- @param {Object} payload
295
- @param {String|Number} id
296
- @param {String} requestType
297
- @return {Object} JSON-API Document
298
- */
299
- normalizeFindAllResponse(store, primaryModelClass, payload, id, requestType) {
300
- return this.normalizeArrayResponse(...arguments);
301
- },
302
- /**
303
- Called by the default normalizeResponse implementation when the
304
- type of request is `findBelongsTo`
305
- @since 1.13.0
306
- @method normalizeFindBelongsToResponse
307
- @public
308
- @param {Store} store
309
- @param {Model} primaryModelClass
310
- @param {Object} payload
311
- @param {String|Number} id
312
- @param {String} requestType
313
- @return {Object} JSON-API Document
314
- */
315
- normalizeFindBelongsToResponse(store, primaryModelClass, payload, id, requestType) {
316
- return this.normalizeSingleResponse(...arguments);
317
- },
318
- /**
319
- Called by the default normalizeResponse implementation when the
320
- type of request is `findHasMany`
321
- @since 1.13.0
322
- @method normalizeFindHasManyResponse
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
- normalizeFindHasManyResponse(store, primaryModelClass, payload, id, requestType) {
332
- return this.normalizeArrayResponse(...arguments);
333
- },
334
- /**
335
- Called by the default normalizeResponse implementation when the
336
- type of request is `findMany`
337
- @since 1.13.0
338
- @method normalizeFindManyResponse
339
- @public
340
- @param {Store} store
341
- @param {Model} primaryModelClass
342
- @param {Object} payload
343
- @param {String|Number} id
344
- @param {String} requestType
345
- @return {Object} JSON-API Document
346
- */
347
- normalizeFindManyResponse(store, primaryModelClass, payload, id, requestType) {
348
- return this.normalizeArrayResponse(...arguments);
349
- },
350
- /**
351
- Called by the default normalizeResponse implementation when the
352
- type of request is `query`
353
- @since 1.13.0
354
- @method normalizeQueryResponse
355
- @public
356
- @param {Store} store
357
- @param {Model} primaryModelClass
358
- @param {Object} payload
359
- @param {String|Number} id
360
- @param {String} requestType
361
- @return {Object} JSON-API Document
362
- */
363
- normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
364
- return this.normalizeArrayResponse(...arguments);
365
- },
366
- /**
367
- Called by the default normalizeResponse implementation when the
368
- type of request is `createRecord`
369
- @since 1.13.0
370
- @method normalizeCreateRecordResponse
371
- @public
372
- @param {Store} store
373
- @param {Model} primaryModelClass
374
- @param {Object} payload
375
- @param {String|Number} id
376
- @param {String} requestType
377
- @return {Object} JSON-API Document
378
- */
379
- normalizeCreateRecordResponse(store, primaryModelClass, payload, id, requestType) {
380
- return this.normalizeSaveResponse(...arguments);
381
- },
382
- /**
383
- Called by the default normalizeResponse implementation when the
384
- type of request is `deleteRecord`
385
- @since 1.13.0
386
- @method normalizeDeleteRecordResponse
387
- @public
388
- @param {Store} store
389
- @param {Model} primaryModelClass
390
- @param {Object} payload
391
- @param {String|Number} id
392
- @param {String} requestType
393
- @return {Object} JSON-API Document
394
- */
395
- normalizeDeleteRecordResponse(store, primaryModelClass, payload, id, requestType) {
396
- return this.normalizeSaveResponse(...arguments);
397
- },
398
- /**
399
- Called by the default normalizeResponse implementation when the
400
- type of request is `updateRecord`
401
- @since 1.13.0
402
- @method normalizeUpdateRecordResponse
403
- @public
404
- @param {Store} store
405
- @param {Model} primaryModelClass
406
- @param {Object} payload
407
- @param {String|Number} id
408
- @param {String} requestType
409
- @return {Object} JSON-API Document
410
- */
411
- normalizeUpdateRecordResponse(store, primaryModelClass, payload, id, requestType) {
412
- return this.normalizeSaveResponse(...arguments);
413
- },
414
- /**
415
- normalizeUpdateRecordResponse, normalizeCreateRecordResponse and
416
- normalizeDeleteRecordResponse delegate to this method by default.
417
- @since 1.13.0
418
- @method normalizeSaveResponse
419
- @public
420
- @param {Store} store
421
- @param {Model} primaryModelClass
422
- @param {Object} payload
423
- @param {String|Number} id
424
- @param {String} requestType
425
- @return {Object} JSON-API Document
426
- */
427
- normalizeSaveResponse(store, primaryModelClass, payload, id, requestType) {
428
- return this.normalizeSingleResponse(...arguments);
429
- },
430
- /**
431
- normalizeQueryResponse and normalizeFindRecordResponse delegate to this
432
- method by default.
433
- @since 1.13.0
434
- @method normalizeSingleResponse
435
- @public
436
- @param {Store} store
437
- @param {Model} primaryModelClass
438
- @param {Object} payload
439
- @param {String|Number} id
440
- @param {String} requestType
441
- @return {Object} JSON-API Document
442
- */
443
- normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) {
444
- return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true);
445
- },
446
- /**
447
- normalizeQueryResponse, normalizeFindManyResponse, and normalizeFindHasManyResponse delegate
448
- to this method by default.
449
- @since 1.13.0
450
- @method normalizeArrayResponse
451
- @public
452
- @param {Store} store
453
- @param {Model} primaryModelClass
454
- @param {Object} payload
455
- @param {String|Number} id
456
- @param {String} requestType
457
- @return {Object} JSON-API Document
458
- */
459
- normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
460
- return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false);
461
- },
462
- /**
463
- @method _normalizeResponse
464
- @param {Store} store
465
- @param {Model} primaryModelClass
466
- @param {Object} payload
467
- @param {String|Number} id
468
- @param {String} requestType
469
- @param {Boolean} isSingle
470
- @return {Object} JSON-API Document
471
- @private
472
- */
473
- _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) {
474
- const documentHash = {
475
- data: null,
476
- included: []
477
- };
478
- const meta = this.extractMeta(store, primaryModelClass, payload);
479
- if (meta) {
480
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
481
- if (!test) {
482
- throw new Error('The `meta` returned from `extractMeta` has to be an object, not "' + typeof meta + '".');
483
- }
484
- })(typeof meta === 'object') : {};
485
- documentHash.meta = meta;
486
- }
487
- if (isSingle) {
488
- const {
489
- data,
490
- included
491
- } = this.normalize(primaryModelClass, payload);
492
- documentHash.data = data;
493
- if (included) {
494
- documentHash.included = included;
495
- }
496
- } else {
497
- const ret = new Array(payload.length);
498
- for (let i = 0, l = payload.length; i < l; i++) {
499
- const item = payload[i];
500
- const {
501
- data,
502
- included
503
- } = this.normalize(primaryModelClass, item);
504
- if (included) {
505
- documentHash.included = documentHash.included.concat(included);
506
- }
507
- ret[i] = data;
508
- }
509
- documentHash.data = ret;
510
- }
511
- return documentHash;
512
- },
513
- /**
514
- Normalizes a part of the JSON payload returned by
515
- the server. You should override this method, munge the hash
516
- and call super if you have generic normalization to do.
517
- It takes the type of the record that is being normalized
518
- (as a Model class), the property where the hash was
519
- originally found, and the hash to normalize.
520
- You can use this method, for example, to normalize underscored keys to camelized
521
- or other general-purpose normalizations.
522
- Example
523
- ```app/serializers/application.js
524
- import JSONSerializer from '@ember-data-mirror/serializer/json';
525
- import { underscore } from '<app-name>/utils/string-utils';
526
- import { get } from '@ember/object';
527
- export default class ApplicationSerializer extends JSONSerializer {
528
- normalize(typeClass, hash) {
529
- let fields = typeClass.fields;
530
- fields.forEach(function(type, field) {
531
- let payloadField = underscore(field);
532
- if (field === payloadField) { return; }
533
- hash[field] = hash[payloadField];
534
- delete hash[payloadField];
535
- });
536
- return super.normalize(...arguments);
537
- }
538
- }
539
- ```
540
- @method normalize
541
- @public
542
- @param {Model} typeClass
543
- @param {Object} hash
544
- @return {Object}
545
- */
546
- normalize(modelClass, resourceHash) {
547
- let data = null;
548
- if (resourceHash) {
549
- this.normalizeUsingDeclaredMapping(modelClass, resourceHash);
550
- if (typeof resourceHash.links === 'object') {
551
- this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links);
552
- }
553
- data = {
554
- id: this.extractId(modelClass, resourceHash),
555
- type: modelClass.modelName,
556
- attributes: this.extractAttributes(modelClass, resourceHash),
557
- relationships: this.extractRelationships(modelClass, resourceHash)
558
- };
559
- if (resourceHash.lid) {
560
- data.lid = resourceHash.lid;
561
- }
562
- this.applyTransforms(modelClass, data.attributes);
563
- }
564
- return {
565
- data
566
- };
567
- },
568
- /**
569
- Returns the resource's ID.
570
- @method extractId
571
- @public
572
- @param {Object} modelClass
573
- @param {Object} resourceHash
574
- @return {String}
575
- */
576
- extractId(modelClass, resourceHash) {
577
- const primaryKey = this.primaryKey;
578
- const id = resourceHash[primaryKey];
579
- return coerceId(id);
580
- },
581
- /**
582
- Returns the resource's attributes formatted as a JSON-API "attributes object".
583
- http://jsonapi.org/format/#document-resource-object-attributes
584
- @method extractAttributes
585
- @public
586
- @param {Object} modelClass
587
- @param {Object} resourceHash
588
- @return {Object}
589
- */
590
- extractAttributes(modelClass, resourceHash) {
591
- let attributeKey;
592
- const attributes = {};
593
- modelClass.eachAttribute(key => {
594
- attributeKey = this.keyForAttribute(key, 'deserialize');
595
- if (resourceHash[attributeKey] !== undefined) {
596
- attributes[key] = resourceHash[attributeKey];
597
- }
598
- });
599
- return attributes;
600
- },
601
- /**
602
- Returns a relationship formatted as a JSON-API "relationship object".
603
- http://jsonapi.org/format/#document-resource-object-relationships
604
- @method extractRelationship
605
- @public
606
- @param {Object} relationshipModelName
607
- @param {Object} relationshipHash
608
- @return {Object}
609
- */
610
- extractRelationship(relationshipModelName, relationshipHash) {
611
- if (!relationshipHash) {
612
- return null;
613
- }
614
- /*
615
- When `relationshipHash` is an object it usually means that the relationship
616
- is polymorphic. It could however also be embedded resources that the
617
- EmbeddedRecordsMixin has be able to process.
618
- */
619
- if (relationshipHash && typeof relationshipHash === 'object' && !Array.isArray(relationshipHash)) {
620
- if (relationshipHash.id) {
621
- relationshipHash.id = coerceId(relationshipHash.id);
622
- }
623
- const modelClass = this.store.modelFor(relationshipModelName);
624
- if (relationshipHash.type && !modelClass.fields.has('type')) {
625
- relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type);
626
- }
627
- return relationshipHash;
628
- }
629
- return {
630
- id: coerceId(relationshipHash),
631
- type: dasherize(singularize(relationshipModelName))
632
- };
633
- },
634
- /**
635
- Returns a polymorphic relationship formatted as a JSON-API "relationship object".
636
- http://jsonapi.org/format/#document-resource-object-relationships
637
- `relationshipOptions` is a hash which contains more information about the
638
- polymorphic relationship which should be extracted:
639
- - `resourceHash` complete hash of the resource the relationship should be
640
- extracted from
641
- - `relationshipKey` key under which the value for the relationship is
642
- extracted from the resourceHash
643
- - `relationshipMeta` meta information about the relationship
644
- @method extractPolymorphicRelationship
645
- @public
646
- @param {Object} relationshipModelName
647
- @param {Object} relationshipHash
648
- @param {Object} relationshipOptions
649
- @return {Object}
650
- */
651
- extractPolymorphicRelationship(relationshipModelName, relationshipHash, relationshipOptions) {
652
- return this.extractRelationship(relationshipModelName, relationshipHash);
653
- },
654
- /**
655
- Returns the resource's relationships formatted as a JSON-API "relationships object".
656
- http://jsonapi.org/format/#document-resource-object-relationships
657
- @method extractRelationships
658
- @public
659
- @param {Object} modelClass
660
- @param {Object} resourceHash
661
- @return {Object}
662
- */
663
- extractRelationships(modelClass, resourceHash) {
664
- const relationships = {};
665
- modelClass.eachRelationship((key, relationshipMeta) => {
666
- let relationship = null;
667
- const relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
668
- if (resourceHash[relationshipKey] !== undefined) {
669
- let data = null;
670
- const relationshipHash = resourceHash[relationshipKey];
671
- if (relationshipMeta.kind === 'belongsTo') {
672
- if (relationshipMeta.options.polymorphic) {
673
- // extracting a polymorphic belongsTo may need more information
674
- // than the type and the hash (which might only be an id) for the
675
- // relationship, hence we pass the key, resource and
676
- // relationshipMeta too
677
- data = this.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, {
678
- key,
679
- resourceHash,
680
- relationshipMeta
681
- });
682
- } else {
683
- data = this.extractRelationship(relationshipMeta.type, relationshipHash);
684
- }
685
- } else if (relationshipMeta.kind === 'hasMany') {
686
- if (relationshipHash) {
687
- data = new Array(relationshipHash.length);
688
- if (relationshipMeta.options.polymorphic) {
689
- for (let i = 0, l = relationshipHash.length; i < l; i++) {
690
- const item = relationshipHash[i];
691
- data[i] = this.extractPolymorphicRelationship(relationshipMeta.type, item, {
692
- key,
693
- resourceHash,
694
- relationshipMeta
695
- });
696
- }
697
- } else {
698
- for (let i = 0, l = relationshipHash.length; i < l; i++) {
699
- const item = relationshipHash[i];
700
- data[i] = this.extractRelationship(relationshipMeta.type, item);
701
- }
702
- }
703
- }
704
- }
705
- relationship = {
706
- data
707
- };
708
- }
709
- const linkKey = this.keyForLink(key, relationshipMeta.kind);
710
- if (resourceHash.links && resourceHash.links[linkKey] !== undefined) {
711
- const related = resourceHash.links[linkKey];
712
- relationship = relationship || {};
713
- relationship.links = {
714
- related
715
- };
716
- }
717
- if (relationship) {
718
- relationships[key] = relationship;
719
- }
720
- });
721
- return relationships;
722
- },
723
- /**
724
- Dasherizes the model name in the payload
725
- @method modelNameFromPayloadKey
726
- @public
727
- @param {String} key
728
- @return {String} the model's modelName
729
- */
730
- modelNameFromPayloadKey(key) {
731
- return dasherize(singularize(key));
732
- },
733
- /**
734
- @method normalizeRelationships
735
- @private
736
- */
737
- normalizeRelationships(typeClass, hash) {
738
- let payloadKey;
739
- if (this.keyForRelationship) {
740
- typeClass.eachRelationship((key, relationship) => {
741
- payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize');
742
- if (key === payloadKey) {
743
- return;
744
- }
745
- if (hash[payloadKey] === undefined) {
746
- return;
747
- }
748
- hash[key] = hash[payloadKey];
749
- delete hash[payloadKey];
750
- });
751
- }
752
- },
753
- /**
754
- @method normalizeUsingDeclaredMapping
755
- @private
756
- */
757
- normalizeUsingDeclaredMapping(modelClass, hash) {
758
- const attrs = this.attrs;
759
- let normalizedKey;
760
- let payloadKey;
761
- if (attrs) {
762
- for (const key in attrs) {
763
- normalizedKey = payloadKey = this._getMappedKey(key, modelClass);
764
- if (hash[payloadKey] === undefined) {
765
- continue;
766
- }
767
- if (modelClass.attributes.has(key)) {
768
- normalizedKey = this.keyForAttribute(key, 'deserialize');
769
- }
770
- if (modelClass.relationshipsByName.has(key)) {
771
- normalizedKey = this.keyForRelationship(key, modelClass, 'deserialize');
772
- }
773
- if (payloadKey !== normalizedKey) {
774
- hash[normalizedKey] = hash[payloadKey];
775
- delete hash[payloadKey];
776
- }
777
- }
778
- }
779
- },
780
- /**
781
- Looks up the property key that was set by the custom `attr` mapping
782
- passed to the serializer.
783
- @method _getMappedKey
784
- @private
785
- @param {String} key
786
- @return {String} key
787
- */
788
- _getMappedKey(key, modelClass) {
789
- warn('There is no attribute or relationship with the name `' + key + '` on `' + modelClass.modelName + '`. Check your serializers attrs hash.', modelClass.attributes.has(key) || modelClass.relationshipsByName.has(key), {
790
- id: 'ds.serializer.no-mapped-attrs-key'
791
- });
792
- const attrs = this.attrs;
793
- let mappedKey;
794
- if (attrs && attrs[key]) {
795
- mappedKey = attrs[key];
796
- //We need to account for both the { title: 'post_title' } and
797
- //{ title: { key: 'post_title' }} forms
798
- if (mappedKey.key) {
799
- mappedKey = mappedKey.key;
800
- }
801
- if (typeof mappedKey === 'string') {
802
- key = mappedKey;
803
- }
804
- }
805
- return key;
806
- },
807
- /**
808
- Check attrs.key.serialize property to inform if the `key`
809
- can be serialized
810
- @method _canSerialize
811
- @private
812
- @param {String} key
813
- @return {Boolean} true if the key can be serialized
814
- */
815
- _canSerialize(key) {
816
- const attrs = this.attrs;
817
- return !attrs || !attrs[key] || attrs[key].serialize !== false;
818
- },
819
- /**
820
- When attrs.key.serialize is set to true then
821
- it takes priority over the other checks and the related
822
- attribute/relationship will be serialized
823
- @method _mustSerialize
824
- @private
825
- @param {String} key
826
- @return {Boolean} true if the key must be serialized
827
- */
828
- _mustSerialize(key) {
829
- const attrs = this.attrs;
830
- return attrs && attrs[key] && attrs[key].serialize === true;
831
- },
832
- /**
833
- Check if the given hasMany relationship should be serialized
834
- By default only many-to-many and many-to-none relationships are serialized.
835
- This could be configured per relationship by Serializer's `attrs` object.
836
- @method shouldSerializeHasMany
837
- @public
838
- @param {Snapshot} snapshot
839
- @param {String} key
840
- @param {RelationshipSchema} relationship
841
- @return {Boolean} true if the hasMany relationship should be serialized
842
- */
843
- shouldSerializeHasMany(snapshot, key, relationship) {
844
- const schema = this.store.modelFor(snapshot.modelName);
845
- const relationshipType = schema.determineRelationshipType(relationship, this.store);
846
- if (this._mustSerialize(key)) {
847
- return true;
848
- }
849
- return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany');
850
- },
851
- // SERIALIZE
852
- /**
853
- Called when a record is saved in order to convert the
854
- record into JSON.
855
- By default, it creates a JSON object with a key for
856
- each attribute and belongsTo relationship.
857
- For example, consider this model:
858
- ```app/models/comment.js
859
- import Model, { attr, belongsTo } from '@ember-data-mirror/model';
860
- export default class CommentModel extends Model {
861
- @attr title;
862
- @attr body;
863
- @belongsTo('user') author;
864
- }
865
- ```
866
- The default serialization would create a JSON object like:
867
- ```javascript
868
- {
869
- "title": "Rails is unagi",
870
- "body": "Rails? Omakase? O_O",
871
- "author": 12
872
- }
873
- ```
874
- By default, attributes are passed through as-is, unless
875
- you specified an attribute type (`attr('date')`). If
876
- you specify a transform, the JavaScript value will be
877
- serialized when inserted into the JSON hash.
878
- By default, belongs-to relationships are converted into
879
- IDs when inserted into the JSON hash.
880
- ## IDs
881
- `serialize` takes an options hash with a single option:
882
- `includeId`. If this option is `true`, `serialize` will,
883
- by default include the ID in the JSON object it builds.
884
- The adapter passes in `includeId: true` when serializing
885
- a record for `createRecord`, but not for `updateRecord`.
886
- ## Customization
887
- Your server may expect a different JSON format than the
888
- built-in serialization format.
889
- In that case, you can implement `serialize` yourself and
890
- return a JSON hash of your choosing.
891
- ```app/serializers/post.js
892
- import JSONSerializer from '@ember-data-mirror/serializer/json';
893
- export default class PostSerializer extends JSONSerializer {
894
- serialize(snapshot, options) {
895
- let json = {
896
- POST_TTL: snapshot.attr('title'),
897
- POST_BDY: snapshot.attr('body'),
898
- POST_CMS: snapshot.hasMany('comments', { ids: true })
899
- };
900
- if (options.includeId) {
901
- json.POST_ID_ = snapshot.id;
902
- }
903
- return json;
904
- }
905
- }
906
- ```
907
- ## Customizing an App-Wide Serializer
908
- If you want to define a serializer for your entire
909
- application, you'll probably want to use `eachAttribute`
910
- and `eachRelationship` on the record.
911
- ```app/serializers/application.js
912
- import JSONSerializer from '@ember-data-mirror/serializer/json';
913
- import { singularize } from '<app-name>/utils/string-utils';
914
- export default class ApplicationSerializer extends JSONSerializer {
915
- serialize(snapshot, options) {
916
- let json = {};
917
- snapshot.eachAttribute((name) => {
918
- json[serverAttributeName(name)] = snapshot.attr(name);
919
- });
920
- snapshot.eachRelationship((name, relationship) => {
921
- if (relationship.kind === 'hasMany') {
922
- json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
923
- }
924
- });
925
- if (options.includeId) {
926
- json.ID_ = snapshot.id;
927
- }
928
- return json;
929
- }
930
- }
931
- function serverAttributeName(attribute) {
932
- return attribute.underscore().toUpperCase();
933
- }
934
- function serverHasManyName(name) {
935
- return serverAttributeName(singularize(name)) + "_IDS";
936
- }
937
- ```
938
- This serializer will generate JSON that looks like this:
939
- ```javascript
940
- {
941
- "TITLE": "Rails is omakase",
942
- "BODY": "Yep. Omakase.",
943
- "COMMENT_IDS": [ "1", "2", "3" ]
944
- }
945
- ```
946
- ## Tweaking the Default JSON
947
- If you just want to do some small tweaks on the default JSON,
948
- you can call `super.serialize` first and make the tweaks on
949
- the returned JSON.
950
- ```app/serializers/post.js
951
- import JSONSerializer from '@ember-data-mirror/serializer/json';
952
- export default class PostSerializer extends JSONSerializer {
953
- serialize(snapshot, options) {
954
- let json = super.serialize(...arguments);
955
- json.subject = json.title;
956
- delete json.title;
957
- return json;
958
- }
959
- }
960
- ```
961
- @method serialize
962
- @public
963
- @param {Snapshot} snapshot
964
- @param {Object} options
965
- @return {Object} json
966
- */
967
- serialize(snapshot, options) {
968
- const json = {};
969
- if (options && options.includeId) {
970
- const id = snapshot.id;
971
- if (id) {
972
- json[this.primaryKey] = id;
973
- }
974
- }
975
- snapshot.eachAttribute((key, attribute) => {
976
- this.serializeAttribute(snapshot, json, key, attribute);
977
- });
978
- snapshot.eachRelationship((key, relationship) => {
979
- if (relationship.kind === 'belongsTo') {
980
- this.serializeBelongsTo(snapshot, json, relationship);
981
- } else if (relationship.kind === 'hasMany') {
982
- this.serializeHasMany(snapshot, json, relationship);
983
- }
984
- });
985
- return json;
986
- },
987
- /**
988
- You can use this method to customize how a serialized record is added to the complete
989
- JSON hash to be sent to the server. By default the JSON Serializer does not namespace
990
- the payload and just sends the raw serialized JSON object.
991
- If your server expects namespaced keys, you should consider using the RESTSerializer.
992
- Otherwise you can override this method to customize how the record is added to the hash.
993
- The hash property should be modified by reference.
994
- For example, your server may expect underscored root objects.
995
- ```app/serializers/application.js
996
- import RESTSerializer from '@ember-data-mirror/serializer/rest';
997
- import { underscoren} from '<app-name>/utils/string-utils';
998
- export default class ApplicationSerializer extends RESTSerializer {
999
- serializeIntoHash(data, type, snapshot, options) {
1000
- let root = underscore(type.modelName);
1001
- data[root] = this.serialize(snapshot, options);
1002
- }
1003
- }
1004
- ```
1005
- @method serializeIntoHash
1006
- @public
1007
- @param {Object} hash
1008
- @param {Model} typeClass
1009
- @param {Snapshot} snapshot
1010
- @param {Object} options
1011
- */
1012
- serializeIntoHash(hash, typeClass, snapshot, options) {
1013
- Object.assign(hash, this.serialize(snapshot, options));
1014
- },
1015
- /**
1016
- `serializeAttribute` can be used to customize how `attr`
1017
- properties are serialized
1018
- For example if you wanted to ensure all your attributes were always
1019
- serialized as properties on an `attributes` object you could
1020
- write:
1021
- ```app/serializers/application.js
1022
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1023
- export default class ApplicationSerializer extends JSONSerializer {
1024
- serializeAttribute(snapshot, json, key, attributes) {
1025
- json.attributes = json.attributes || {};
1026
- super.serializeAttribute(snapshot, json.attributes, key, attributes);
1027
- }
1028
- }
1029
- ```
1030
- @method serializeAttribute
1031
- @public
1032
- @param {Snapshot} snapshot
1033
- @param {Object} json
1034
- @param {String} key
1035
- @param {Object} attribute
1036
- */
1037
- serializeAttribute(snapshot, json, key, attribute) {
1038
- if (this._canSerialize(key)) {
1039
- const type = attribute.type;
1040
- let value = snapshot.attr(key);
1041
- if (type) {
1042
- const transform = this.transformFor(type);
1043
- value = transform.serialize(value, attribute.options);
1044
- }
1045
-
1046
- // if provided, use the mapping provided by `attrs` in
1047
- // the serializer
1048
- const schema = this.store.modelFor(snapshot.modelName);
1049
- let payloadKey = this._getMappedKey(key, schema);
1050
- if (payloadKey === key && this.keyForAttribute) {
1051
- payloadKey = this.keyForAttribute(key, 'serialize');
1052
- }
1053
- json[payloadKey] = value;
1054
- }
1055
- },
1056
- /**
1057
- `serializeBelongsTo` can be used to customize how `belongsTo`
1058
- properties are serialized.
1059
- Example
1060
- ```app/serializers/post.js
1061
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1062
- export default class PostSerializer extends JSONSerializer {
1063
- serializeBelongsTo(snapshot, json, relationship) {
1064
- let key = relationship.name;
1065
- let belongsTo = snapshot.belongsTo(key);
1066
- key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key;
1067
- json[key] = !belongsTo ? null : belongsTo.record.toJSON();
1068
- }
1069
- }
1070
- ```
1071
- @method serializeBelongsTo
1072
- @public
1073
- @param {Snapshot} snapshot
1074
- @param {Object} json
1075
- @param {Object} relationship
1076
- */
1077
- serializeBelongsTo(snapshot, json, relationship) {
1078
- const name = relationship.name;
1079
- if (this._canSerialize(name)) {
1080
- const belongsToId = snapshot.belongsTo(name, {
1081
- id: true
1082
- });
1083
-
1084
- // if provided, use the mapping provided by `attrs` in
1085
- // the serializer
1086
- const schema = this.store.modelFor(snapshot.modelName);
1087
- let payloadKey = this._getMappedKey(name, schema);
1088
- if (payloadKey === name && this.keyForRelationship) {
1089
- payloadKey = this.keyForRelationship(name, 'belongsTo', 'serialize');
1090
- }
1091
-
1092
- //Need to check whether the id is there for new&async records
1093
- if (!belongsToId) {
1094
- json[payloadKey] = null;
1095
- } else {
1096
- json[payloadKey] = belongsToId;
1097
- }
1098
- if (relationship.options.polymorphic) {
1099
- this.serializePolymorphicType(snapshot, json, relationship);
1100
- }
1101
- }
1102
- },
1103
- /**
1104
- `serializeHasMany` can be used to customize how `hasMany`
1105
- properties are serialized.
1106
- Example
1107
- ```app/serializers/post.js
1108
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1109
- export default class PostSerializer extends JSONSerializer {
1110
- serializeHasMany(snapshot, json, relationship) {
1111
- let key = relationship.name;
1112
- if (key === 'comments') {
1113
- return;
1114
- } else {
1115
- super.serializeHasMany(...arguments);
1116
- }
1117
- }
1118
- }
1119
- ```
1120
- @method serializeHasMany
1121
- @public
1122
- @param {Snapshot} snapshot
1123
- @param {Object} json
1124
- @param {Object} relationship
1125
- */
1126
- serializeHasMany(snapshot, json, relationship) {
1127
- const name = relationship.name;
1128
- if (this.shouldSerializeHasMany(snapshot, name, relationship)) {
1129
- const hasMany = snapshot.hasMany(name, {
1130
- ids: true
1131
- });
1132
- if (hasMany !== undefined) {
1133
- // if provided, use the mapping provided by `attrs` in
1134
- // the serializer
1135
- const schema = this.store.modelFor(snapshot.modelName);
1136
- let payloadKey = this._getMappedKey(name, schema);
1137
- if (payloadKey === name && this.keyForRelationship) {
1138
- payloadKey = this.keyForRelationship(name, 'hasMany', 'serialize');
1139
- }
1140
- json[payloadKey] = hasMany;
1141
- // TODO support for polymorphic manyToNone and manyToMany relationships
1142
- }
1143
- }
1144
- },
1145
- /**
1146
- You can use this method to customize how polymorphic objects are
1147
- serialized. Objects are considered to be polymorphic if
1148
- `{ polymorphic: true }` is pass as the second argument to the
1149
- `belongsTo` function.
1150
- Example
1151
- ```app/serializers/comment.js
1152
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1153
- export default class CommentSerializer extends JSONSerializer {
1154
- serializePolymorphicType(snapshot, json, relationship) {
1155
- let key = relationship.name;
1156
- let belongsTo = snapshot.belongsTo(key);
1157
- key = this.keyForAttribute ? this.keyForAttribute(key, 'serialize') : key;
1158
- if (!belongsTo) {
1159
- json[key + '_type'] = null;
1160
- } else {
1161
- json[key + '_type'] = belongsTo.modelName;
1162
- }
1163
- }
1164
- }
1165
- ```
1166
- @method serializePolymorphicType
1167
- @public
1168
- @param {Snapshot} snapshot
1169
- @param {Object} json
1170
- @param {Object} relationship
1171
- */
1172
- serializePolymorphicType() {},
1173
- /**
1174
- `extractMeta` is used to deserialize any meta information in the
1175
- adapter payload. By default Ember Data expects meta information to
1176
- be located on the `meta` property of the payload object.
1177
- Example
1178
- ```app/serializers/post.js
1179
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1180
- export default class PostSerializer extends JSONSerializer {
1181
- extractMeta(store, typeClass, payload) {
1182
- if (payload && payload.hasOwnProperty('_pagination')) {
1183
- let meta = payload._pagination;
1184
- delete payload._pagination;
1185
- return meta;
1186
- }
1187
- }
1188
- }
1189
- ```
1190
- @method extractMeta
1191
- @public
1192
- @param {Store} store
1193
- @param {Model} modelClass
1194
- @param {Object} payload
1195
- */
1196
- extractMeta(store, modelClass, payload) {
1197
- if (payload && payload['meta'] !== undefined) {
1198
- const meta = payload.meta;
1199
- delete payload.meta;
1200
- return meta;
1201
- }
1202
- },
1203
- /**
1204
- `extractErrors` is used to extract model errors when a call
1205
- to `Model#save` fails with an `InvalidError`. By default
1206
- Ember Data expects error information to be located on the `errors`
1207
- property of the payload object.
1208
- This serializer expects this `errors` object to be an Array similar
1209
- to the following, compliant with the https://jsonapi.org/format/#errors specification:
1210
- ```js
1211
- {
1212
- "errors": [
1213
- {
1214
- "detail": "This username is already taken!",
1215
- "source": {
1216
- "pointer": "data/attributes/username"
1217
- }
1218
- }, {
1219
- "detail": "Doesn't look like a valid email.",
1220
- "source": {
1221
- "pointer": "data/attributes/email"
1222
- }
1223
- }
1224
- ]
1225
- }
1226
- ```
1227
- The key `detail` provides a textual description of the problem.
1228
- Alternatively, the key `title` can be used for the same purpose.
1229
- The nested keys `source.pointer` detail which specific element
1230
- of the request data was invalid.
1231
- Note that JSON-API also allows for object-level errors to be placed
1232
- in an object with pointer `data`, signifying that the problem
1233
- cannot be traced to a specific attribute:
1234
- ```javascript
1235
- {
1236
- "errors": [
1237
- {
1238
- "detail": "Some generic non property error message",
1239
- "source": {
1240
- "pointer": "data"
1241
- }
1242
- }
1243
- ]
1244
- }
1245
- ```
1246
- When turn into a `Errors` object, you can read these errors
1247
- through the property `base`:
1248
- ```handlebars
1249
- {{#each @model.errors.base as |error|}}
1250
- <div class="error">
1251
- {{error.message}}
1252
- </div>
1253
- {{/each}}
1254
- ```
1255
- Example of alternative implementation, overriding the default
1256
- behavior to deal with a different format of errors:
1257
- ```app/serializers/post.js
1258
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1259
- export default class PostSerializer extends JSONSerializer {
1260
- extractErrors(store, typeClass, payload, id) {
1261
- if (payload && typeof payload === 'object' && payload._problems) {
1262
- payload = payload._problems;
1263
- this.normalizeErrors(typeClass, payload);
1264
- }
1265
- return payload;
1266
- }
1267
- }
1268
- ```
1269
- @method extractErrors
1270
- @public
1271
- @param {Store} store
1272
- @param {Model} typeClass
1273
- @param {Object} payload
1274
- @param {(String|Number)} id
1275
- @return {Object} json The deserialized errors
1276
- */
1277
- extractErrors(store, typeClass, payload, id) {
1278
- if (payload && typeof payload === 'object' && payload.errors) {
1279
- // the default assumption is that errors is already in JSON:API format
1280
- const extracted = {};
1281
- payload.errors.forEach(error => {
1282
- if (error.source && error.source.pointer) {
1283
- let key = error.source.pointer.match(SOURCE_POINTER_REGEXP);
1284
- if (key) {
1285
- key = key[2];
1286
- } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
1287
- key = PRIMARY_ATTRIBUTE_KEY;
1288
- }
1289
- if (key) {
1290
- extracted[key] = extracted[key] || [];
1291
- extracted[key].push(error.detail || error.title);
1292
- }
1293
- }
1294
- });
1295
-
1296
- // if the user has an attrs hash, convert keys using it
1297
- this.normalizeUsingDeclaredMapping(typeClass, extracted);
1298
-
1299
- // for each attr and relationship, make sure that we use
1300
- // the normalized key
1301
- typeClass.eachAttribute(name => {
1302
- const key = this.keyForAttribute(name, 'deserialize');
1303
- if (key !== name && extracted[key] !== undefined) {
1304
- extracted[name] = extracted[key];
1305
- delete extracted[key];
1306
- }
1307
- });
1308
- typeClass.eachRelationship(name => {
1309
- const key = this.keyForRelationship(name, 'deserialize');
1310
- if (key !== name && extracted[key] !== undefined) {
1311
- extracted[name] = extracted[key];
1312
- delete extracted[key];
1313
- }
1314
- });
1315
- return extracted;
1316
- }
1317
- return payload;
1318
- },
1319
- /**
1320
- `keyForAttribute` can be used to define rules for how to convert an
1321
- attribute name in your model to a key in your JSON.
1322
- Example
1323
- ```app/serializers/application.js
1324
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1325
- import { underscore } from '<app-name>/utils/string-utils';
1326
- export default class ApplicationSerializer extends JSONSerializer {
1327
- keyForAttribute(attr, method) {
1328
- return underscore(attr).toUpperCase();
1329
- }
1330
- }
1331
- ```
1332
- @method keyForAttribute
1333
- @public
1334
- @param {String} key
1335
- @param {String} method
1336
- @return {String} normalized key
1337
- */
1338
- keyForAttribute(key, method) {
1339
- return key;
1340
- },
1341
- /**
1342
- `keyForRelationship` can be used to define a custom key when
1343
- serializing and deserializing relationship properties. By default
1344
- `JSONSerializer` does not provide an implementation of this method.
1345
- Example
1346
- ```app/serializers/post.js
1347
- import JSONSerializer from '@ember-data-mirror/serializer/json';
1348
- import { underscore } from '<app-name>/utils/string-utils';
1349
- export default class PostSerializer extends JSONSerializer {
1350
- keyForRelationship(key, relationship, method) {
1351
- return `rel_${underscore(key)}`;
1352
- }
1353
- }
1354
- ```
1355
- @method keyForRelationship
1356
- @public
1357
- @param {String} key
1358
- @param {String} typeClass
1359
- @param {String} method
1360
- @return {String} normalized key
1361
- */
1362
- keyForRelationship(key, typeClass, method) {
1363
- return key;
1364
- },
1365
- /**
1366
- `keyForLink` can be used to define a custom key when deserializing link
1367
- properties.
1368
- @method keyForLink
1369
- @public
1370
- @param {String} key
1371
- @param {String} kind `belongsTo` or `hasMany`
1372
- @return {String} normalized key
1373
- */
1374
- keyForLink(key, kind) {
1375
- return key;
1376
- },
1377
- // HELPERS
1378
-
1379
- /**
1380
- @method transformFor
1381
- @private
1382
- @param {String} attributeType
1383
- @param {Boolean} skipAssertion
1384
- @return {Transform} transform
1385
- */
1386
- transformFor(attributeType, skipAssertion) {
1387
- const transform = getOwner(this).lookup('transform:' + attributeType);
1388
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
1389
- if (!test) {
1390
- throw new Error(`Unable to find the transform for \`attr('${attributeType}')\``);
1391
- }
1392
- })(skipAssertion || !!transform) : {};
1393
- return transform;
1394
- }
1395
- });
1396
- export { JSONSerializer as J, coerceId as c };