@warp-drive/legacy 5.9.0-alpha.2 → 5.9.0-alpha.21

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