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