@warp-drive/legacy 5.8.0-beta.0 → 5.8.0-beta.2

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