@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,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
+ 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
+ // @ts-expect-error untyped
387
+ documentHash.meta = meta;
388
+ }
389
+ if (isSingle) {
390
+ // @ts-expect-error untyped
391
+ const {
392
+ data,
393
+ included
394
+ } = this.normalize(primaryModelClass, payload);
395
+ documentHash.data = data;
396
+ if (included) {
397
+ documentHash.included = included;
398
+ }
399
+ } else {
400
+ // @ts-expect-error untyped
401
+ const ret = new Array(payload.length);
402
+ // @ts-expect-error untyped
403
+ for (let i = 0, l = payload.length; i < l; i++) {
404
+ const item = payload[i];
405
+ // @ts-expect-error untyped
406
+ const {
407
+ data,
408
+ included
409
+ } = this.normalize(primaryModelClass, item);
410
+ if (included) {
411
+ documentHash.included = documentHash.included.concat(included);
412
+ }
413
+ ret[i] = data;
414
+ }
415
+
416
+ // @ts-expect-error untyped
417
+ documentHash.data = ret;
418
+ }
419
+ return documentHash;
420
+ },
421
+ /**
422
+ Normalizes a part of the JSON payload returned by
423
+ the server. You should override this method, munge the hash
424
+ and call super if you have generic normalization to do.
425
+ It takes the type of the record that is being normalized
426
+ (as a Model class), the property where the hash was
427
+ originally found, and the hash to normalize.
428
+ You can use this method, for example, to normalize underscored keys to camelized
429
+ or other general-purpose normalizations.
430
+ Example
431
+ ```js [app/serializers/application.js]
432
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
433
+ import { underscore } from '<app-name>/utils/string-utils';
434
+ import { get } from '@ember/object';
435
+ export default class ApplicationSerializer extends JSONSerializer {
436
+ normalize(typeClass, hash) {
437
+ let fields = typeClass.fields;
438
+ fields.forEach(function(type, field) {
439
+ let payloadField = underscore(field);
440
+ if (field === payloadField) { return; }
441
+ hash[field] = hash[payloadField];
442
+ delete hash[payloadField];
443
+ });
444
+ return super.normalize(...arguments);
445
+ }
446
+ }
447
+ ```
448
+ @public
449
+ @param {Model} typeClass
450
+ @param {Object} hash
451
+ @return {Object}
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
+ @param {Object} modelClass
498
+ @param {Object} resourceHash
499
+ @return {Object}
500
+ */
501
+ extractAttributes(modelClass, resourceHash) {
502
+ let attributeKey;
503
+ const attributes = {};
504
+ modelClass.eachAttribute(key => {
505
+ attributeKey = this.keyForAttribute(key, 'deserialize');
506
+ if (resourceHash[attributeKey] !== undefined) {
507
+ attributes[key] = resourceHash[attributeKey];
508
+ }
509
+ });
510
+ return attributes;
511
+ },
512
+ /**
513
+ Returns a relationship formatted as a JSON-API "relationship object".
514
+ http://jsonapi.org/format/#document-resource-object-relationships
515
+ @public
516
+ */
517
+ extractRelationship(relationshipModelName, relationshipHash) {
518
+ if (!relationshipHash) {
519
+ return null;
520
+ }
521
+ /*
522
+ When `relationshipHash` is an object it usually means that the relationship
523
+ is polymorphic. It could however also be embedded resources that the
524
+ EmbeddedRecordsMixin has be able to process.
525
+ */
526
+ if (relationshipHash && typeof relationshipHash === 'object' && !Array.isArray(relationshipHash)) {
527
+ // @ts-expect-error untyped
528
+ if (relationshipHash.id) {
529
+ // @ts-expect-error untyped
530
+ relationshipHash.id = coerceId(relationshipHash.id);
531
+ }
532
+
533
+ // @ts-expect-error store is dynamically injected
534
+ const modelClass = this.store.modelFor(relationshipModelName);
535
+ // @ts-expect-error untyped
536
+ if (relationshipHash.type && !modelClass.fields.has('type')) {
537
+ // @ts-expect-error untyped
538
+ relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type);
539
+ }
540
+ return relationshipHash;
541
+ }
542
+ return {
543
+ id: coerceId(relationshipHash),
544
+ type: dasherize(singularize(relationshipModelName))
545
+ };
546
+ },
547
+ /**
548
+ Returns a polymorphic relationship formatted as a JSON-API "relationship object".
549
+ http://jsonapi.org/format/#document-resource-object-relationships
550
+ `relationshipOptions` is a hash which contains more information about the
551
+ polymorphic relationship which should be extracted:
552
+ - `resourceHash` complete hash of the resource the relationship should be
553
+ extracted from
554
+ - `relationshipKey` key under which the value for the relationship is
555
+ extracted from the resourceHash
556
+ - `relationshipMeta` meta information about the relationship
557
+ @public
558
+ */
559
+ extractPolymorphicRelationship(relationshipModelName, relationshipHash, relationshipOptions) {
560
+ return this.extractRelationship(relationshipModelName, relationshipHash);
561
+ },
562
+ /**
563
+ Returns the resource's relationships formatted as a JSON-API "relationships object".
564
+ http://jsonapi.org/format/#document-resource-object-relationships
565
+ @public
566
+ */
567
+ extractRelationships(modelClass, resourceHash) {
568
+ const relationships = {};
569
+ modelClass.eachRelationship((key, relationshipMeta) => {
570
+ let relationship = null;
571
+ const relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
572
+ if (resourceHash[relationshipKey] !== undefined) {
573
+ let data = null;
574
+ const relationshipHash = resourceHash[relationshipKey];
575
+ if (relationshipMeta.kind === 'belongsTo') {
576
+ if (relationshipMeta.options.polymorphic) {
577
+ // extracting a polymorphic belongsTo may need more information
578
+ // than the type and the hash (which might only be an id) for the
579
+ // relationship, hence we pass the key, resource and
580
+ // relationshipMeta too
581
+ // @ts-expect-error untyped
582
+ data = this.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, {
583
+ key,
584
+ resourceHash,
585
+ relationshipMeta
586
+ });
587
+ } else {
588
+ // @ts-expect-error untyped
589
+ data = this.extractRelationship(relationshipMeta.type, relationshipHash);
590
+ }
591
+ } else if (relationshipMeta.kind === 'hasMany') {
592
+ if (relationshipHash) {
593
+ // @ts-expect-error untyped
594
+ data = new Array(relationshipHash.length);
595
+ if (relationshipMeta.options.polymorphic) {
596
+ for (let i = 0, l = relationshipHash.length; i < l; i++) {
597
+ const item = relationshipHash[i];
598
+ // @ts-expect-error untyped
599
+ data[i] = this.extractPolymorphicRelationship(relationshipMeta.type, item, {
600
+ key,
601
+ resourceHash,
602
+ relationshipMeta
603
+ });
604
+ }
605
+ } else {
606
+ for (let i = 0, l = relationshipHash.length; i < l; i++) {
607
+ const item = relationshipHash[i];
608
+ // @ts-expect-error untyped
609
+ data[i] = this.extractRelationship(relationshipMeta.type, item);
610
+ }
611
+ }
612
+ }
613
+ }
614
+ // @ts-expect-error untyped
615
+ relationship = {
616
+ data
617
+ };
618
+ }
619
+ const linkKey = this.keyForLink(key, relationshipMeta.kind);
620
+ // @ts-expect-error untyped
621
+ if (resourceHash.links && resourceHash.links[linkKey] !== undefined) {
622
+ // @ts-expect-error untyped
623
+ const related = resourceHash.links[linkKey];
624
+ // @ts-expect-error untyped
625
+ relationship = relationship || {};
626
+ // @ts-expect-error untyped
627
+ relationship.links = {
628
+ related
629
+ };
630
+ }
631
+ if (relationship) {
632
+ relationships[key] = relationship;
633
+ }
634
+ });
635
+ return relationships;
636
+ },
637
+ /**
638
+ Dasherizes the model name in the payload
639
+ @public
640
+ @param {String} key
641
+ @return {String} the model's modelName
642
+ */
643
+ modelNameFromPayloadKey(key) {
644
+ return dasherize(singularize(key));
645
+ },
646
+ /**
647
+ @private
648
+ */
649
+ normalizeRelationships(typeClass, hash) {
650
+ let payloadKey;
651
+ if (this.keyForRelationship) {
652
+ typeClass.eachRelationship((key, relationship) => {
653
+ payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize');
654
+ if (key === payloadKey) {
655
+ return;
656
+ }
657
+ if (hash[payloadKey] === undefined) {
658
+ return;
659
+ }
660
+ hash[key] = hash[payloadKey];
661
+ delete hash[payloadKey];
662
+ });
663
+ }
664
+ },
665
+ /**
666
+ @private
667
+ */
668
+ normalizeUsingDeclaredMapping(modelClass, hash) {
669
+ // @ts-expect-error attrs is dynamically injected
670
+ const attrs = this.attrs;
671
+ let normalizedKey;
672
+ let payloadKey;
673
+ if (attrs) {
674
+ for (const key in attrs) {
675
+ normalizedKey = payloadKey = this._getMappedKey(key, modelClass);
676
+ if (hash[payloadKey] === undefined) {
677
+ continue;
678
+ }
679
+ if (modelClass.attributes.has(key)) {
680
+ normalizedKey = this.keyForAttribute(key, 'deserialize');
681
+ }
682
+ if (modelClass.relationshipsByName.has(key)) {
683
+ normalizedKey = this.keyForRelationship(key, modelClass, 'deserialize');
684
+ }
685
+ if (payloadKey !== normalizedKey) {
686
+ hash[normalizedKey] = hash[payloadKey];
687
+ delete hash[payloadKey];
688
+ }
689
+ }
690
+ }
691
+ },
692
+ /**
693
+ Looks up the property key that was set by the custom `attr` mapping
694
+ passed to the serializer.
695
+ @private
696
+ */
697
+ _getMappedKey(key, modelClass) {
698
+ const attrs = this.attrs;
699
+ let mappedKey;
700
+ if (attrs && attrs[key]) {
701
+ mappedKey = attrs[key];
702
+ //We need to account for both the { title: 'post_title' } and
703
+ //{ title: { key: 'post_title' }} forms
704
+ if (mappedKey.key) {
705
+ mappedKey = mappedKey.key;
706
+ }
707
+ if (typeof mappedKey === 'string') {
708
+ key = mappedKey;
709
+ }
710
+ }
711
+ return key;
712
+ },
713
+ /**
714
+ Check attrs.key.serialize property to inform if the `key`
715
+ can be serialized
716
+ @private
717
+ @return true if the key can be serialized
718
+ */
719
+ _canSerialize(key) {
720
+ // @ts-expect-error no idea what attrs is here
721
+ const attrs = this.attrs;
722
+ return !attrs || !attrs[key] || attrs[key].serialize !== false;
723
+ },
724
+ /**
725
+ When attrs.key.serialize is set to true then
726
+ it takes priority over the other checks and the related
727
+ attribute/relationship will be serialized
728
+ @private
729
+ @return true if the key must be serialized
730
+ */
731
+ _mustSerialize(key) {
732
+ // @ts-expect-error no idea what attrs is here
733
+ const attrs = this.attrs;
734
+ return attrs && attrs[key] && attrs[key].serialize === true;
735
+ },
736
+ /**
737
+ Check if the given hasMany relationship should be serialized
738
+ By default only many-to-many and many-to-none relationships are serialized.
739
+ This could be configured per relationship by Serializer's `attrs` object.
740
+ @public
741
+ @return true if the hasMany relationship should be serialized
742
+ */
743
+ shouldSerializeHasMany(snapshot, key, relationship) {
744
+ // @ts-expect-error store is dynamically injected
745
+ const schema = this.store.modelFor(snapshot.modelName);
746
+ // @ts-expect-error store is dynamically injected
747
+ const relationshipType = schema.determineRelationshipType(relationship, this.store);
748
+ if (this._mustSerialize(key)) {
749
+ return true;
750
+ }
751
+ return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany');
752
+ },
753
+ // SERIALIZE
754
+ /**
755
+ Called when a record is saved in order to convert the
756
+ record into JSON.
757
+ By default, it creates a JSON object with a key for
758
+ each attribute and belongsTo relationship.
759
+ For example, consider this model:
760
+ ```js [app/models/comment.js]
761
+ import Model, { attr, belongsTo } from '@warp-drive/legacy/model';
762
+ export default class CommentModel extends Model {
763
+ @attr title;
764
+ @attr body;
765
+ @belongsTo('user') author;
766
+ }
767
+ ```
768
+ The default serialization would create a JSON object like:
769
+ ```javascript
770
+ {
771
+ "title": "Rails is unagi",
772
+ "body": "Rails? Omakase? O_O",
773
+ "author": 12
774
+ }
775
+ ```
776
+ By default, attributes are passed through as-is, unless
777
+ you specified an attribute type (`attr('date')`). If
778
+ you specify a transform, the JavaScript value will be
779
+ serialized when inserted into the JSON hash.
780
+ By default, belongs-to relationships are converted into
781
+ IDs when inserted into the JSON hash.
782
+ ## IDs
783
+ `serialize` takes an options hash with a single option:
784
+ `includeId`. If this option is `true`, `serialize` will,
785
+ by default include the ID in the JSON object it builds.
786
+ The adapter passes in `includeId: true` when serializing
787
+ a record for `createRecord`, but not for `updateRecord`.
788
+ ## Customization
789
+ Your server may expect a different JSON format than the
790
+ built-in serialization format.
791
+ In that case, you can implement `serialize` yourself and
792
+ return a JSON hash of your choosing.
793
+ ```js [app/serializers/post.js]
794
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
795
+ export default class PostSerializer extends JSONSerializer {
796
+ serialize(snapshot, options) {
797
+ let json = {
798
+ POST_TTL: snapshot.attr('title'),
799
+ POST_BDY: snapshot.attr('body'),
800
+ POST_CMS: snapshot.hasMany('comments', { ids: true })
801
+ };
802
+ if (options.includeId) {
803
+ json.POST_ID_ = snapshot.id;
804
+ }
805
+ return json;
806
+ }
807
+ }
808
+ ```
809
+ ## Customizing an App-Wide Serializer
810
+ If you want to define a serializer for your entire
811
+ application, you'll probably want to use `eachAttribute`
812
+ and `eachRelationship` on the record.
813
+ ```js [app/serializers/application.js]
814
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
815
+ import { singularize } from '<app-name>/utils/string-utils';
816
+ export default class ApplicationSerializer extends JSONSerializer {
817
+ serialize(snapshot, options) {
818
+ let json = {};
819
+ snapshot.eachAttribute((name) => {
820
+ json[serverAttributeName(name)] = snapshot.attr(name);
821
+ });
822
+ snapshot.eachRelationship((name, relationship) => {
823
+ if (relationship.kind === 'hasMany') {
824
+ json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
825
+ }
826
+ });
827
+ if (options.includeId) {
828
+ json.ID_ = snapshot.id;
829
+ }
830
+ return json;
831
+ }
832
+ }
833
+ function serverAttributeName(attribute) {
834
+ return attribute.underscore().toUpperCase();
835
+ }
836
+ function serverHasManyName(name) {
837
+ return serverAttributeName(singularize(name)) + "_IDS";
838
+ }
839
+ ```
840
+ This serializer will generate JSON that looks like this:
841
+ ```javascript
842
+ {
843
+ "TITLE": "Rails is omakase",
844
+ "BODY": "Yep. Omakase.",
845
+ "COMMENT_IDS": [ "1", "2", "3" ]
846
+ }
847
+ ```
848
+ ## Tweaking the Default JSON
849
+ If you just want to do some small tweaks on the default JSON,
850
+ you can call `super.serialize` first and make the tweaks on
851
+ the returned JSON.
852
+ ```js [app/serializers/post.js]
853
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
854
+ export default class PostSerializer extends JSONSerializer {
855
+ serialize(snapshot, options) {
856
+ let json = super.serialize(...arguments);
857
+ json.subject = json.title;
858
+ delete json.title;
859
+ return json;
860
+ }
861
+ }
862
+ ```
863
+ @public
864
+ */
865
+ serialize(snapshot, options) {
866
+ const json = {};
867
+
868
+ // @ts-expect-error super loose typing here right now
869
+ if (options && options.includeId) {
870
+ const id = snapshot.id;
871
+ if (id) {
872
+ json[this.primaryKey] = id;
873
+ }
874
+ }
875
+ snapshot.eachAttribute((key, attribute) => {
876
+ this.serializeAttribute(snapshot, json, key, attribute);
877
+ });
878
+ snapshot.eachRelationship((key, relationship) => {
879
+ if (relationship.kind === 'belongsTo') {
880
+ this.serializeBelongsTo(snapshot, json, relationship);
881
+ } else if (relationship.kind === 'hasMany') {
882
+ this.serializeHasMany(snapshot, json, relationship);
883
+ }
884
+ });
885
+ return json;
886
+ },
887
+ /**
888
+ You can use this method to customize how a serialized record is added to the complete
889
+ JSON hash to be sent to the server. By default the JSON Serializer does not namespace
890
+ the payload and just sends the raw serialized JSON object.
891
+ If your server expects namespaced keys, you should consider using the RESTSerializer.
892
+ Otherwise you can override this method to customize how the record is added to the hash.
893
+ The hash property should be modified by reference.
894
+ For example, your server may expect underscored root objects.
895
+ ```js [app/serializers/application.js]
896
+ import RESTSerializer from '@warp-drive/legacy/serializer/rest';
897
+ import { underscoren} from '<app-name>/utils/string-utils';
898
+ export default class ApplicationSerializer extends RESTSerializer {
899
+ serializeIntoHash(data, type, snapshot, options) {
900
+ let root = underscore(type.modelName);
901
+ data[root] = this.serialize(snapshot, options);
902
+ }
903
+ }
904
+ ```
905
+ @public
906
+ */
907
+ serializeIntoHash(hash, typeClass, snapshot, options) {
908
+ Object.assign(hash, this.serialize(snapshot, options));
909
+ },
910
+ /**
911
+ `serializeAttribute` can be used to customize how `attr`
912
+ properties are serialized
913
+ For example if you wanted to ensure all your attributes were always
914
+ serialized as properties on an `attributes` object you could
915
+ write:
916
+ ```js [app/serializers/application.js]
917
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
918
+ export default class ApplicationSerializer extends JSONSerializer {
919
+ serializeAttribute(snapshot, json, key, attributes) {
920
+ json.attributes = json.attributes || {};
921
+ super.serializeAttribute(snapshot, json.attributes, key, attributes);
922
+ }
923
+ }
924
+ ```
925
+ @public
926
+ */
927
+ serializeAttribute(snapshot, json, key, attribute) {
928
+ if (this._canSerialize(key)) {
929
+ const type = attribute.type;
930
+ // @ts-expect-error we don't know what is on the snapshot
931
+ let value = snapshot.attr(key);
932
+ if (type) {
933
+ const transform = this.transformFor(type);
934
+ value = transform.serialize(value, attribute.options);
935
+ }
936
+
937
+ // if provided, use the mapping provided by `attrs` in
938
+ // the serializer
939
+ // @ts-expect-error store added dynamically
940
+ const schema = this.store.modelFor(snapshot.modelName);
941
+ let payloadKey = this._getMappedKey(key, schema);
942
+ if (payloadKey === key && this.keyForAttribute) {
943
+ payloadKey = this.keyForAttribute(key, 'serialize');
944
+ }
945
+ json[payloadKey] = value;
946
+ }
947
+ },
948
+ /**
949
+ `serializeBelongsTo` can be used to customize how `belongsTo`
950
+ properties are serialized.
951
+ Example
952
+ ```js [app/serializers/post.js]
953
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
954
+ export default class PostSerializer extends JSONSerializer {
955
+ serializeBelongsTo(snapshot, json, relationship) {
956
+ let key = relationship.name;
957
+ let belongsTo = snapshot.belongsTo(key);
958
+ key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key;
959
+ json[key] = !belongsTo ? null : belongsTo.record.toJSON();
960
+ }
961
+ }
962
+ ```
963
+ @public
964
+ */
965
+ serializeBelongsTo(snapshot, json, relationship) {
966
+ const name = relationship.name;
967
+ if (this._canSerialize(name)) {
968
+ const belongsToId = snapshot.belongsTo(name, {
969
+ id: true
970
+ });
971
+
972
+ // if provided, use the mapping provided by `attrs` in
973
+ // the serializer
974
+ // @ts-expect-error store added dynamically
975
+ const schema = this.store.modelFor(snapshot.modelName);
976
+ let payloadKey = this._getMappedKey(name, schema);
977
+ if (payloadKey === name && this.keyForRelationship) {
978
+ payloadKey = this.keyForRelationship(name, 'belongsTo', 'serialize');
979
+ }
980
+
981
+ //Need to check whether the id is there for new&async records
982
+ if (!belongsToId) {
983
+ json[payloadKey] = null;
984
+ } else {
985
+ json[payloadKey] = belongsToId;
986
+ }
987
+ if (relationship.options.polymorphic) {
988
+ this.serializePolymorphicType(snapshot, json, relationship);
989
+ }
990
+ }
991
+ },
992
+ /**
993
+ `serializeHasMany` can be used to customize how `hasMany`
994
+ properties are serialized.
995
+ Example
996
+ ```js [app/serializers/post.js]
997
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
998
+ export default class PostSerializer extends JSONSerializer {
999
+ serializeHasMany(snapshot, json, relationship) {
1000
+ let key = relationship.name;
1001
+ if (key === 'comments') {
1002
+ return;
1003
+ } else {
1004
+ super.serializeHasMany(...arguments);
1005
+ }
1006
+ }
1007
+ }
1008
+ ```
1009
+ @public
1010
+ */
1011
+ serializeHasMany(snapshot, json, relationship) {
1012
+ const name = relationship.name;
1013
+ if (this.shouldSerializeHasMany(snapshot, name, relationship)) {
1014
+ const hasMany = snapshot.hasMany(name, {
1015
+ ids: true
1016
+ });
1017
+ if (hasMany !== undefined) {
1018
+ // if provided, use the mapping provided by `attrs` in
1019
+ // the serializer
1020
+ // @ts-expect-error store added dynamically
1021
+ const schema = this.store.modelFor(snapshot.modelName);
1022
+ let payloadKey = this._getMappedKey(name, schema);
1023
+ if (payloadKey === name && this.keyForRelationship) {
1024
+ payloadKey = this.keyForRelationship(name, 'hasMany', 'serialize');
1025
+ }
1026
+ json[payloadKey] = hasMany;
1027
+ // TODO support for polymorphic manyToNone and manyToMany relationships
1028
+ }
1029
+ }
1030
+ },
1031
+ /**
1032
+ You can use this method to customize how polymorphic objects are
1033
+ serialized. Objects are considered to be polymorphic if
1034
+ `{ polymorphic: true }` is pass as the second argument to the
1035
+ `belongsTo` function.
1036
+ Example
1037
+ ```js [app/serializers/comment.js]
1038
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
1039
+ export default class CommentSerializer extends JSONSerializer {
1040
+ serializePolymorphicType(snapshot, json, relationship) {
1041
+ let key = relationship.name;
1042
+ let belongsTo = snapshot.belongsTo(key);
1043
+ key = this.keyForAttribute ? this.keyForAttribute(key, 'serialize') : key;
1044
+ if (!belongsTo) {
1045
+ json[key + '_type'] = null;
1046
+ } else {
1047
+ json[key + '_type'] = belongsTo.modelName;
1048
+ }
1049
+ }
1050
+ }
1051
+ ```
1052
+ @public
1053
+ */
1054
+ serializePolymorphicType(snapshot, json, relationship) {},
1055
+ /**
1056
+ `extractMeta` is used to deserialize any meta information in the
1057
+ adapter payload. By default Ember Data expects meta information to
1058
+ be located on the `meta` property of the payload object.
1059
+ Example
1060
+ ```js [app/serializers/post.js]
1061
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
1062
+ export default class PostSerializer extends JSONSerializer {
1063
+ extractMeta(store, typeClass, payload) {
1064
+ if (payload && payload.hasOwnProperty('_pagination')) {
1065
+ let meta = payload._pagination;
1066
+ delete payload._pagination;
1067
+ return meta;
1068
+ }
1069
+ }
1070
+ }
1071
+ ```
1072
+ @public
1073
+ */
1074
+ extractMeta(store, modelClass, payload) {
1075
+ if (payload && payload['meta'] !== undefined) {
1076
+ // @ts-expect-error
1077
+ const meta = payload.meta;
1078
+ // @ts-expect-error
1079
+ delete payload.meta;
1080
+ return meta;
1081
+ }
1082
+ },
1083
+ /**
1084
+ `extractErrors` is used to extract model errors when a call
1085
+ to `Model#save` fails with an `InvalidError`. By default
1086
+ Ember Data expects error information to be located on the `errors`
1087
+ property of the payload object.
1088
+ This serializer expects this `errors` object to be an Array similar
1089
+ to the following, compliant with the https://jsonapi.org/format/#errors specification:
1090
+ ```js
1091
+ {
1092
+ "errors": [
1093
+ {
1094
+ "detail": "This username is already taken!",
1095
+ "source": {
1096
+ "pointer": "data/attributes/username"
1097
+ }
1098
+ }, {
1099
+ "detail": "Doesn't look like a valid email.",
1100
+ "source": {
1101
+ "pointer": "data/attributes/email"
1102
+ }
1103
+ }
1104
+ ]
1105
+ }
1106
+ ```
1107
+ The key `detail` provides a textual description of the problem.
1108
+ Alternatively, the key `title` can be used for the same purpose.
1109
+ The nested keys `source.pointer` detail which specific element
1110
+ of the request data was invalid.
1111
+ Note that JSON-API also allows for object-level errors to be placed
1112
+ in an object with pointer `data`, signifying that the problem
1113
+ cannot be traced to a specific attribute:
1114
+ ```javascript
1115
+ {
1116
+ "errors": [
1117
+ {
1118
+ "detail": "Some generic non property error message",
1119
+ "source": {
1120
+ "pointer": "data"
1121
+ }
1122
+ }
1123
+ ]
1124
+ }
1125
+ ```
1126
+ When turn into a `Errors` object, you can read these errors
1127
+ through the property `base`:
1128
+ ```handlebars
1129
+ {{#each @model.errors.base as |error|}}
1130
+ <div class="error">
1131
+ {{error.message}}
1132
+ </div>
1133
+ {{/each}}
1134
+ ```
1135
+ Example of alternative implementation, overriding the default
1136
+ behavior to deal with a different format of errors:
1137
+ ```js [app/serializers/post.js]
1138
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
1139
+ export default class PostSerializer extends JSONSerializer {
1140
+ extractErrors(store, typeClass, payload, id) {
1141
+ if (payload && typeof payload === 'object' && payload._problems) {
1142
+ payload = payload._problems;
1143
+ this.normalizeErrors(typeClass, payload);
1144
+ }
1145
+ return payload;
1146
+ }
1147
+ }
1148
+ ```
1149
+ @public
1150
+ @param {Store} store
1151
+ @param {Model} typeClass
1152
+ @param {Object} payload
1153
+ @param {(String|Number)} id
1154
+ @return {Object} json The deserialized errors
1155
+ */
1156
+ extractErrors(store, typeClass, payload, id) {
1157
+ // @ts-expect-error
1158
+ if (payload && typeof payload === 'object' && payload.errors) {
1159
+ // the default assumption is that errors is already in JSON:API format
1160
+ const extracted = {};
1161
+
1162
+ // @ts-expect-error
1163
+ payload.errors.forEach(error => {
1164
+ if (error.source && error.source.pointer) {
1165
+ let key = error.source.pointer.match(SOURCE_POINTER_REGEXP);
1166
+ if (key) {
1167
+ key = key[2];
1168
+ } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
1169
+ key = PRIMARY_ATTRIBUTE_KEY;
1170
+ }
1171
+ if (key) {
1172
+ extracted[key] = extracted[key] || [];
1173
+ extracted[key].push(error.detail || error.title);
1174
+ }
1175
+ }
1176
+ });
1177
+
1178
+ // if the user has an attrs hash, convert keys using it
1179
+ this.normalizeUsingDeclaredMapping(typeClass, extracted);
1180
+
1181
+ // for each attr and relationship, make sure that we use
1182
+ // the normalized key
1183
+ typeClass.eachAttribute(name => {
1184
+ const key = this.keyForAttribute(name, 'deserialize');
1185
+ if (key !== name && extracted[key] !== undefined) {
1186
+ extracted[name] = extracted[key];
1187
+ delete extracted[key];
1188
+ }
1189
+ });
1190
+ typeClass.eachRelationship(name => {
1191
+ const key = this.keyForRelationship(name, 'deserialize');
1192
+ if (key !== name && extracted[key] !== undefined) {
1193
+ extracted[name] = extracted[key];
1194
+ delete extracted[key];
1195
+ }
1196
+ });
1197
+ return extracted;
1198
+ }
1199
+ return payload;
1200
+ },
1201
+ /**
1202
+ `keyForAttribute` can be used to define rules for how to convert an
1203
+ attribute name in your model to a key in your JSON.
1204
+ Example
1205
+ ```js [app/serializers/application.js]
1206
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
1207
+ import { underscore } from '<app-name>/utils/string-utils';
1208
+ export default class ApplicationSerializer extends JSONSerializer {
1209
+ keyForAttribute(attr, method) {
1210
+ return underscore(attr).toUpperCase();
1211
+ }
1212
+ }
1213
+ ```
1214
+ @public
1215
+ */
1216
+ keyForAttribute(key, method) {
1217
+ return key;
1218
+ },
1219
+ /**
1220
+ `keyForRelationship` can be used to define a custom key when
1221
+ serializing and deserializing relationship properties. By default
1222
+ `JSONSerializer` does not provide an implementation of this method.
1223
+ Example
1224
+ ```js [app/serializers/post.js]
1225
+ import { JSONSerializer } from '@warp-drive/legacy/serializer/json';
1226
+ import { underscore } from '<app-name>/utils/string-utils';
1227
+ export default class PostSerializer extends JSONSerializer {
1228
+ keyForRelationship(key, relationship, method) {
1229
+ return `rel_${underscore(key)}`;
1230
+ }
1231
+ }
1232
+ ```
1233
+ @public
1234
+ */
1235
+ keyForRelationship(key, typeClass, method) {
1236
+ return key;
1237
+ },
1238
+ /**
1239
+ `keyForLink` can be used to define a custom key when deserializing link
1240
+ properties.
1241
+ @public
1242
+ */
1243
+ keyForLink(key, kind) {
1244
+ return key;
1245
+ },
1246
+ // HELPERS
1247
+
1248
+ /**
1249
+ @private
1250
+ */
1251
+ transformFor(attributeType, skipAssertion) {
1252
+ const transform = getOwner(this).lookup(`transform:${attributeType}`);
1253
+ return transform;
1254
+ }
1255
+ });
1256
+ export { JSONSerializer as J, coerceId as c };