@ember-data-mirror/serializer 5.6.0-alpha.5 → 5.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/addon-main.cjs +1 -1
  2. package/dist/index.js +1 -301
  3. package/dist/json-api.js +1 -514
  4. package/dist/json.js +1 -6
  5. package/dist/rest.js +1 -1245
  6. package/dist/transform.js +1 -313
  7. package/package.json +7 -20
  8. package/unstable-preview-types/index.d.ts +81 -238
  9. package/unstable-preview-types/json-api.d.ts +2 -497
  10. package/unstable-preview-types/json.d.ts +2 -1048
  11. package/unstable-preview-types/rest.d.ts +2 -555
  12. package/unstable-preview-types/transform.d.ts +3 -7
  13. package/dist/index.js.map +0 -1
  14. package/dist/json-CYP2BhR9.js +0 -1349
  15. package/dist/json-CYP2BhR9.js.map +0 -1
  16. package/dist/json-api.js.map +0 -1
  17. package/dist/json.js.map +0 -1
  18. package/dist/rest.js.map +0 -1
  19. package/dist/transform.js.map +0 -1
  20. package/unstable-preview-types/-private/embedded-records-mixin.d.ts +0 -99
  21. package/unstable-preview-types/-private/embedded-records-mixin.d.ts.map +0 -1
  22. package/unstable-preview-types/-private/transforms/boolean.d.ts +0 -49
  23. package/unstable-preview-types/-private/transforms/boolean.d.ts.map +0 -1
  24. package/unstable-preview-types/-private/transforms/boolean.type-test.d.ts +0 -4
  25. package/unstable-preview-types/-private/transforms/boolean.type-test.d.ts.map +0 -1
  26. package/unstable-preview-types/-private/transforms/date.d.ts +0 -30
  27. package/unstable-preview-types/-private/transforms/date.d.ts.map +0 -1
  28. package/unstable-preview-types/-private/transforms/number.d.ts +0 -31
  29. package/unstable-preview-types/-private/transforms/number.d.ts.map +0 -1
  30. package/unstable-preview-types/-private/transforms/string.d.ts +0 -31
  31. package/unstable-preview-types/-private/transforms/string.d.ts.map +0 -1
  32. package/unstable-preview-types/-private/transforms/transform.d.ts +0 -121
  33. package/unstable-preview-types/-private/transforms/transform.d.ts.map +0 -1
  34. package/unstable-preview-types/-private/utils.d.ts +0 -6
  35. package/unstable-preview-types/-private/utils.d.ts.map +0 -1
  36. package/unstable-preview-types/index.d.ts.map +0 -1
  37. package/unstable-preview-types/json-api.d.ts.map +0 -1
  38. package/unstable-preview-types/json.d.ts.map +0 -1
  39. package/unstable-preview-types/rest.d.ts.map +0 -1
  40. package/unstable-preview-types/transform.d.ts.map +0 -1
package/dist/json-api.js CHANGED
@@ -1,514 +1 @@
1
- import { warn } from '@ember/debug';
2
- import { dasherize, pluralize, singularize } from '@ember-data-mirror/request-utils/string';
3
- import { J as JSONSerializer } from "./json-CYP2BhR9.js";
4
- import { macroCondition, getGlobalConfig } from '@embroider/macros';
5
- const JSONAPISerializer = JSONSerializer.extend({
6
- /**
7
- @param {Object} documentHash
8
- @return {Object}
9
- @private
10
- */
11
- _normalizeDocumentHelper(documentHash) {
12
- if (Array.isArray(documentHash.data)) {
13
- const ret = new Array(documentHash.data.length);
14
- for (let i = 0; i < documentHash.data.length; i++) {
15
- const data = documentHash.data[i];
16
- ret[i] = this._normalizeResourceHelper(data);
17
- }
18
- documentHash.data = ret;
19
- } else if (documentHash.data && typeof documentHash.data === 'object') {
20
- documentHash.data = this._normalizeResourceHelper(documentHash.data);
21
- }
22
- if (Array.isArray(documentHash.included)) {
23
- const ret = new Array();
24
- for (let i = 0; i < documentHash.included.length; i++) {
25
- const included = documentHash.included[i];
26
- const normalized = this._normalizeResourceHelper(included);
27
- if (normalized !== null) {
28
- // can be null when unknown type is encountered
29
- ret.push(normalized);
30
- }
31
- }
32
- documentHash.included = ret;
33
- }
34
- return documentHash;
35
- },
36
- /**
37
- @param {Object} relationshipDataHash
38
- @return {Object}
39
- @private
40
- */
41
- _normalizeRelationshipDataHelper(relationshipDataHash) {
42
- relationshipDataHash.type = this.modelNameFromPayloadKey(relationshipDataHash.type);
43
- return relationshipDataHash;
44
- },
45
- /**
46
- @param {Object} resourceHash
47
- @return {Object}
48
- @private
49
- */
50
- _normalizeResourceHelper(resourceHash) {
51
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
52
- if (!test) {
53
- throw new Error(this.warnMessageForUndefinedType());
54
- }
55
- })(resourceHash.type) : {};
56
- const type = this.modelNameFromPayloadKey(resourceHash.type);
57
- if (!this.store.schema.hasResource({
58
- type
59
- })) {
60
- if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
61
- warn(this.warnMessageNoModelForType(type, resourceHash.type, 'modelNameFromPayloadKey'), false, {
62
- id: 'ds.serializer.model-for-type-missing'
63
- });
64
- }
65
- return null;
66
- }
67
- const modelClass = this.store.modelFor(type);
68
- const serializer = this.store.serializerFor(type);
69
- const {
70
- data
71
- } = serializer.normalize(modelClass, resourceHash);
72
- return data;
73
- },
74
- /**
75
- Normalize some data and push it into the store.
76
- @public
77
- @param {Store} store
78
- @param {Object} payload
79
- */
80
- pushPayload(store, payload) {
81
- const normalizedPayload = this._normalizeDocumentHelper(payload);
82
- store.push(normalizedPayload);
83
- },
84
- /**
85
- @param {Store} store
86
- @param {Model} primaryModelClass
87
- @param {Object} payload
88
- @param {String|Number} id
89
- @param {String} requestType
90
- @param {Boolean} isSingle
91
- @return {Object} JSON-API Document
92
- @private
93
- */
94
- _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) {
95
- const normalizedPayload = this._normalizeDocumentHelper(payload);
96
- return normalizedPayload;
97
- },
98
- normalizeQueryRecordResponse() {
99
- const normalized = this._super(...arguments);
100
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
101
- if (!test) {
102
- throw new Error('Expected the primary data returned by the serializer for a `queryRecord` response to be a single object but instead it was an array.');
103
- }
104
- })(!Array.isArray(normalized.data)) : {};
105
- return normalized;
106
- },
107
- extractAttributes(modelClass, resourceHash) {
108
- const attributes = {};
109
- if (resourceHash.attributes) {
110
- modelClass.eachAttribute(key => {
111
- const attributeKey = this.keyForAttribute(key, 'deserialize');
112
- if (resourceHash.attributes[attributeKey] !== undefined) {
113
- attributes[key] = resourceHash.attributes[attributeKey];
114
- }
115
- if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
116
- if (resourceHash.attributes[attributeKey] === undefined && resourceHash.attributes[key] !== undefined) {
117
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
118
- {
119
- throw new Error(`Your payload for '${modelClass.modelName}' contains '${key}', but your serializer is setup to look for '${attributeKey}'. This is most likely because Ember Data's JSON API serializer dasherizes attribute keys by default. You should subclass JSONAPISerializer and implement 'keyForAttribute(key) { return key; }' to prevent Ember Data from customizing your attribute keys.`);
120
- }
121
- })() : {};
122
- }
123
- }
124
- });
125
- }
126
- return attributes;
127
- },
128
- /**
129
- Returns a relationship formatted as a JSON-API "relationship object".
130
- http://jsonapi.org/format/#document-resource-object-relationships
131
- @public
132
- @param {Object} relationshipHash
133
- @return {Object}
134
- */
135
- extractRelationship(relationshipHash) {
136
- if (Array.isArray(relationshipHash.data)) {
137
- const ret = new Array(relationshipHash.data.length);
138
- for (let i = 0; i < relationshipHash.data.length; i++) {
139
- const data = relationshipHash.data[i];
140
- ret[i] = this._normalizeRelationshipDataHelper(data);
141
- }
142
- relationshipHash.data = ret;
143
- } else if (relationshipHash.data && typeof relationshipHash.data === 'object') {
144
- relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data);
145
- }
146
- return relationshipHash;
147
- },
148
- /**
149
- Returns the resource's relationships formatted as a JSON-API "relationships object".
150
- http://jsonapi.org/format/#document-resource-object-relationships
151
- @public
152
- @param {Object} modelClass
153
- @param {Object} resourceHash
154
- @return {Object}
155
- */
156
- extractRelationships(modelClass, resourceHash) {
157
- const relationships = {};
158
- if (resourceHash.relationships) {
159
- modelClass.eachRelationship((key, relationshipMeta) => {
160
- const relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
161
- if (resourceHash.relationships[relationshipKey] !== undefined) {
162
- const relationshipHash = resourceHash.relationships[relationshipKey];
163
- relationships[key] = this.extractRelationship(relationshipHash);
164
- }
165
- if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
166
- if (resourceHash.relationships[relationshipKey] === undefined && resourceHash.relationships[key] !== undefined) {
167
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
168
- {
169
- throw new Error(`Your payload for '${modelClass.modelName}' contains '${key}', but your serializer is setup to look for '${relationshipKey}'. This is most likely because Ember Data's JSON API serializer dasherizes relationship keys by default. You should subclass JSONAPISerializer and implement 'keyForRelationship(key) { return key; }' to prevent Ember Data from customizing your relationship keys.`);
170
- }
171
- })() : {};
172
- }
173
- }
174
- });
175
- }
176
- return relationships;
177
- },
178
- /**
179
- @param {Model} modelClass
180
- @param {Object} resourceHash
181
- @return {String}
182
- @private
183
- */
184
- _extractType(modelClass, resourceHash) {
185
- return this.modelNameFromPayloadKey(resourceHash.type);
186
- },
187
- /**
188
- Dasherizes and singularizes the model name in the payload to match
189
- the format Ember Data uses internally for the model name.
190
- For example the key `posts` would be converted to `post` and the
191
- key `studentAssesments` would be converted to `student-assesment`.
192
- @public
193
- @param {String} key
194
- @return {String} the model's modelName
195
- */
196
- modelNameFromPayloadKey(key) {
197
- return dasherize(singularize(key));
198
- },
199
- /**
200
- Converts the model name to a pluralized version of the model name.
201
- For example `post` would be converted to `posts` and
202
- `student-assesment` would be converted to `student-assesments`.
203
- @public
204
- @param {String} modelName
205
- @return {String}
206
- */
207
- payloadKeyFromModelName(modelName) {
208
- return pluralize(modelName);
209
- },
210
- normalize(modelClass, resourceHash) {
211
- if (resourceHash.attributes) {
212
- this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes);
213
- }
214
- if (resourceHash.relationships) {
215
- this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships);
216
- }
217
- const data = {
218
- id: this.extractId(modelClass, resourceHash),
219
- type: this._extractType(modelClass, resourceHash),
220
- attributes: this.extractAttributes(modelClass, resourceHash),
221
- relationships: this.extractRelationships(modelClass, resourceHash)
222
- };
223
- if (resourceHash.lid) {
224
- data.lid = resourceHash.lid;
225
- }
226
- this.applyTransforms(modelClass, data.attributes);
227
- return {
228
- data
229
- };
230
- },
231
- /**
232
- `keyForAttribute` can be used to define rules for how to convert an
233
- attribute name in your model to a key in your JSON.
234
- By default `JSONAPISerializer` follows the format used on the examples of
235
- http://jsonapi.org/format and uses dashes as the word separator in the JSON
236
- attribute keys.
237
- This behaviour can be easily customized by extending this method.
238
- Example
239
- ```js [app/serializers/application.js]
240
- import JSONAPISerializer from '@ember-data-mirror/serializer/json-api';
241
- import { dasherize } from '<app-name>/utils/string-utils';
242
- export default class ApplicationSerializer extends JSONAPISerializer {
243
- keyForAttribute(attr, method) {
244
- return dasherize(attr).toUpperCase();
245
- }
246
- }
247
- ```
248
- @public
249
- @param {String} key
250
- @param {String} method
251
- @return {String} normalized key
252
- */
253
- keyForAttribute(key, method) {
254
- return dasherize(key);
255
- },
256
- /**
257
- `keyForRelationship` can be used to define a custom key when
258
- serializing and deserializing relationship properties.
259
- By default `JSONAPISerializer` follows the format used on the examples of
260
- http://jsonapi.org/format and uses dashes as word separators in
261
- relationship properties.
262
- This behaviour can be easily customized by extending this method.
263
- Example
264
- ```js [app/serializers/post.js]
265
- import JSONAPISerializer from '@ember-data-mirror/serializer/json-api';
266
- import { underscore } from '<app-name>/utils/string-utils';
267
- export default class ApplicationSerializer extends JSONAPISerializer {
268
- keyForRelationship(key, relationship, method) {
269
- return underscore(key);
270
- }
271
- }
272
- ```
273
- @public
274
- @param {String} key
275
- @param {String} typeClass
276
- @param {String} method
277
- @return {String} normalized key
278
- */
279
- keyForRelationship(key, typeClass, method) {
280
- return dasherize(key);
281
- },
282
- /**
283
- Called when a record is saved in order to convert the
284
- record into JSON.
285
- For example, consider this model:
286
- ```js [app/models/comment.js]
287
- import Model, { attr, belongsTo } from '@ember-data-mirror/model';
288
- export default class CommentModel extends Model {
289
- @attr title;
290
- @attr body;
291
- @belongsTo('user', { async: false, inverse: null })
292
- author;
293
- }
294
- ```
295
- The default serialization would create a JSON-API resource object like:
296
- ```javascript
297
- {
298
- "data": {
299
- "type": "comments",
300
- "attributes": {
301
- "title": "Rails is unagi",
302
- "body": "Rails? Omakase? O_O",
303
- },
304
- "relationships": {
305
- "author": {
306
- "data": {
307
- "id": "12",
308
- "type": "users"
309
- }
310
- }
311
- }
312
- }
313
- }
314
- ```
315
- By default, attributes are passed through as-is, unless
316
- you specified an attribute type (`attr('date')`). If
317
- you specify a transform, the JavaScript value will be
318
- serialized when inserted into the attributes hash.
319
- Belongs-to relationships are converted into JSON-API
320
- resource identifier objects.
321
- ## IDs
322
- `serialize` takes an options hash with a single option:
323
- `includeId`. If this option is `true`, `serialize` will,
324
- by default include the ID in the JSON object it builds.
325
- The JSONAPIAdapter passes in `includeId: true` when serializing a record
326
- for `createRecord` or `updateRecord`.
327
- ## Customization
328
- Your server may expect data in a different format than the
329
- built-in serialization format.
330
- In that case, you can implement `serialize` yourself and
331
- return data formatted to match your API's expectations, or override
332
- the invoked adapter method and do the serialization in the adapter directly
333
- by using the provided snapshot.
334
- If your API's format differs greatly from the JSON:API spec, you should
335
- consider authoring your own adapter and serializer instead of extending
336
- this class.
337
- ```js [app/serializers/post.js]
338
- import JSONAPISerializer from '@ember-data-mirror/serializer/json-api';
339
- export default class PostSerializer extends JSONAPISerializer {
340
- serialize(snapshot, options) {
341
- let json = {
342
- POST_TTL: snapshot.attr('title'),
343
- POST_BDY: snapshot.attr('body'),
344
- POST_CMS: snapshot.hasMany('comments', { ids: true })
345
- };
346
- if (options.includeId) {
347
- json.POST_ID_ = snapshot.id;
348
- }
349
- return json;
350
- }
351
- }
352
- ```
353
- ## Customizing an App-Wide Serializer
354
- If you want to define a serializer for your entire
355
- application, you'll probably want to use `eachAttribute`
356
- and `eachRelationship` on the record.
357
- ```js [app/serializers/application.js]
358
- import JSONAPISerializer from '@ember-data-mirror/serializer/json-api';
359
- import { underscore, singularize } from '<app-name>/utils/string-utils';
360
- export default class ApplicationSerializer extends JSONAPISerializer {
361
- serialize(snapshot, options) {
362
- let json = {};
363
- snapshot.eachAttribute((name) => {
364
- json[serverAttributeName(name)] = snapshot.attr(name);
365
- });
366
- snapshot.eachRelationship((name, relationship) => {
367
- if (relationship.kind === 'hasMany') {
368
- json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
369
- }
370
- });
371
- if (options.includeId) {
372
- json.ID_ = snapshot.id;
373
- }
374
- return json;
375
- }
376
- }
377
- function serverAttributeName(attribute) {
378
- return underscore(attribute).toUpperCase();
379
- }
380
- function serverHasManyName(name) {
381
- return serverAttributeName(singularize(name)) + '_IDS';
382
- }
383
- ```
384
- This serializer will generate JSON that looks like this:
385
- ```javascript
386
- {
387
- "TITLE": "Rails is omakase",
388
- "BODY": "Yep. Omakase.",
389
- "COMMENT_IDS": [ "1", "2", "3" ]
390
- }
391
- ```
392
- ## Tweaking the Default Formatting
393
- If you just want to do some small tweaks on the default JSON:API formatted response,
394
- you can call `super.serialize` first and make the tweaks
395
- on the returned object.
396
- ```js [app/serializers/post.js]
397
- import JSONAPISerializer from '@ember-data-mirror/serializer/json-api';
398
- export default class PostSerializer extends JSONAPISerializer {
399
- serialize(snapshot, options) {
400
- let json = super.serialize(...arguments);
401
- json.data.attributes.subject = json.data.attributes.title;
402
- delete json.data.attributes.title;
403
- return json;
404
- }
405
- }
406
- ```
407
- @public
408
- @param {Snapshot} snapshot
409
- @param {Object} options
410
- @return {Object} json
411
- */
412
- serialize(snapshot, options) {
413
- const data = this._super(...arguments);
414
- data.type = this.payloadKeyFromModelName(snapshot.modelName);
415
- return {
416
- data
417
- };
418
- },
419
- serializeAttribute(snapshot, json, key, attribute) {
420
- const type = attribute.type;
421
- if (this._canSerialize(key)) {
422
- json.attributes = json.attributes || {};
423
- let value = snapshot.attr(key);
424
- if (type) {
425
- const transform = this.transformFor(type);
426
- value = transform.serialize(value, attribute.options);
427
- }
428
- const schema = this.store.modelFor(snapshot.modelName);
429
- let payloadKey = this._getMappedKey(key, schema);
430
- if (payloadKey === key) {
431
- payloadKey = this.keyForAttribute(key, 'serialize');
432
- }
433
- json.attributes[payloadKey] = value;
434
- }
435
- },
436
- serializeBelongsTo(snapshot, json, relationship) {
437
- const name = relationship.name;
438
- if (this._canSerialize(name)) {
439
- const belongsTo = snapshot.belongsTo(name);
440
- const belongsToIsNotNew = belongsTo && !belongsTo.isNew;
441
- if (belongsTo === null || belongsToIsNotNew) {
442
- json.relationships = json.relationships || {};
443
- const schema = this.store.modelFor(snapshot.modelName);
444
- let payloadKey = this._getMappedKey(name, schema);
445
- if (payloadKey === name) {
446
- payloadKey = this.keyForRelationship(name, 'belongsTo', 'serialize');
447
- }
448
- let data = null;
449
- if (belongsTo) {
450
- const payloadType = this.payloadKeyFromModelName(belongsTo.modelName);
451
- data = {
452
- type: payloadType,
453
- id: belongsTo.id
454
- };
455
- }
456
- json.relationships[payloadKey] = {
457
- data
458
- };
459
- }
460
- }
461
- },
462
- serializeHasMany(snapshot, json, relationship) {
463
- const name = relationship.name;
464
- if (this.shouldSerializeHasMany(snapshot, name, relationship)) {
465
- const hasMany = snapshot.hasMany(name);
466
- if (hasMany !== undefined) {
467
- json.relationships = json.relationships || {};
468
- const schema = this.store.modelFor(snapshot.modelName);
469
- let payloadKey = this._getMappedKey(name, schema);
470
- if (payloadKey === name && this.keyForRelationship) {
471
- payloadKey = this.keyForRelationship(name, 'hasMany', 'serialize');
472
- }
473
-
474
- // only serialize has many relationships that are not new
475
- const nonNewHasMany = hasMany.filter(item => !item.isNew);
476
- const data = new Array(nonNewHasMany.length);
477
- for (let i = 0; i < nonNewHasMany.length; i++) {
478
- const item = hasMany[i];
479
- const payloadType = this.payloadKeyFromModelName(item.modelName);
480
- data[i] = {
481
- type: payloadType,
482
- id: item.id
483
- };
484
- }
485
- json.relationships[payloadKey] = {
486
- data
487
- };
488
- }
489
- }
490
- }
491
- });
492
- if (macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG)) {
493
- JSONAPISerializer.reopen({
494
- init(...args) {
495
- this._super(...args);
496
- macroCondition(getGlobalConfig().WarpDriveMirror.env.DEBUG) ? (test => {
497
- if (!test) {
498
- throw new Error(`You've used the EmbeddedRecordsMixin in ${this.toString()} which is not fully compatible with the JSON:API specification. Please confirm that this works for your specific API and add \`this.isEmbeddedRecordsMixinCompatible = true\` to your serializer.`);
499
- }
500
- })(!this.isEmbeddedRecordsMixin || this.isEmbeddedRecordsMixinCompatible === true) : {};
501
- const constructor = this.constructor;
502
- warn(`You've defined 'extractMeta' in ${constructor.toString()} which is not used for serializers extending JSONAPISerializer. Read more at https://api.emberjs.com/ember-data/release/classes/JSONAPISerializer on how to customize meta when using JSON API.`, this.extractMeta === JSONSerializer.prototype.extractMeta, {
503
- id: 'ds.serializer.json-api.extractMeta'
504
- });
505
- },
506
- warnMessageForUndefinedType() {
507
- return 'Encountered a resource object with an undefined type (resolved resource using ' + this.constructor.toString() + ')';
508
- },
509
- warnMessageNoModelForType(modelName, originalType, usedLookup) {
510
- return `Encountered a resource object with type "${originalType}", but no model was found for model name "${modelName}" (resolved model name using '${this.constructor.toString()}.${usedLookup}("${originalType}")').`;
511
- }
512
- });
513
- }
514
- export { JSONAPISerializer as default };
1
+ export { JSONAPISerializer as default } from '@warp-drive-mirror/legacy/serializer/json-api';
package/dist/json.js CHANGED
@@ -1,6 +1 @@
1
- import '@ember/application';
2
- import '@ember/debug';
3
- import '@ember-data-mirror/request-utils/string';
4
- import "./index.js";
5
- export { J as default } from "./json-CYP2BhR9.js";
6
- import '@embroider/macros';
1
+ export { JSONSerializer as default } from '@warp-drive-mirror/legacy/serializer/json';