@warp-drive/legacy 5.6.0-alpha.11

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