@warp-drive/legacy 5.8.0-alpha.4 → 5.8.0-alpha.40

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