@warp-drive/legacy 5.8.0-beta.0 → 5.8.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.
- package/README.md +16 -26
- package/declarations/adapter/error.d.ts +7 -7
- package/declarations/adapter/json-api.d.ts +6 -8
- package/declarations/adapter/rest.d.ts +26 -112
- package/declarations/adapter.d.ts +6 -8
- package/declarations/compat/-private.d.ts +1 -1
- package/declarations/compat/builders/find-all.d.ts +6 -6
- package/declarations/compat/builders/find-record.d.ts +8 -8
- package/declarations/compat/builders/query.d.ts +12 -12
- package/declarations/compat/extensions.d.ts +1 -1
- package/declarations/compat/legacy-network-handler/minimum-adapter-interface.d.ts +7 -9
- package/declarations/compat/legacy-network-handler/minimum-serializer-interface.d.ts +20 -30
- package/declarations/compat/utils.d.ts +17 -17
- package/declarations/compat.d.ts +35 -11
- package/declarations/index.d.ts +70 -0
- package/declarations/model/-private/attr.d.ts +5 -6
- package/declarations/model/-private/belongs-to.d.ts +4 -5
- package/declarations/model/-private/has-many.d.ts +4 -5
- package/declarations/model/-private/hooks.d.ts +1 -1
- package/declarations/model/-private/legacy-relationships-support.d.ts +2 -2
- package/declarations/model/-private/model.d.ts +18 -59
- package/declarations/model/-private/promise-many-array.d.ts +0 -18
- package/declarations/model/-private/record-state.d.ts +1 -1
- package/declarations/model/-private/references/belongs-to.d.ts +19 -29
- package/declarations/model/-private/references/has-many.d.ts +14 -16
- package/declarations/model/migration-support.d.ts +46 -21
- package/declarations/model-fragments/extensions/fragment-array.d.ts +16 -0
- package/declarations/model-fragments/extensions/fragment.d.ts +15 -0
- package/declarations/model-fragments/hooks/model-for.d.ts +20 -0
- package/declarations/model-fragments/index.d.ts +5 -0
- package/declarations/model-fragments/instance-initializers/fragment-extensions.d.ts +9 -0
- package/declarations/model-fragments/utilities/with-array-defaults.d.ts +15 -0
- package/declarations/model-fragments/utilities/with-fragment-array-defaults.d.ts +20 -0
- package/declarations/model-fragments/utilities/with-fragment-defaults.d.ts +19 -0
- package/declarations/model-fragments/utilities/with-legacy.d.ts +3 -0
- package/declarations/model-fragments.d.ts +9 -0
- package/declarations/model.d.ts +2 -2
- package/declarations/serializer/-private/embedded-records-mixin.d.ts +1 -6
- package/declarations/serializer/-private/transforms/boolean.d.ts +2 -2
- package/declarations/serializer/-private/transforms/date.d.ts +2 -2
- package/declarations/serializer/-private/transforms/number.d.ts +1 -1
- package/declarations/serializer/-private/transforms/string.d.ts +1 -1
- package/declarations/serializer/json-api.d.ts +11 -12
- package/declarations/serializer/json.d.ts +9 -11
- package/declarations/serializer/rest.d.ts +4 -6
- package/declarations/serializer.d.ts +9 -12
- package/dist/{-private-8UmnAf9J.js → -private-BG3bMiKp.js} +3 -2
- package/dist/adapter/-private.js +1 -1
- package/dist/adapter/error.js +14 -15
- package/dist/adapter/json-api.js +4 -1
- package/dist/adapter/rest.js +38 -125
- package/dist/adapter.js +6 -8
- package/dist/compat/-private.js +1 -1
- package/dist/compat/builders.js +26 -26
- package/dist/compat/utils.js +17 -18
- package/dist/compat.js +61 -43
- package/dist/{errors-8kD2mSe_.js → errors-Cz5KrzBk.js} +115 -122
- package/dist/hooks-D6diaM34.js +74 -0
- package/dist/index.js +195 -0
- package/dist/{json-Et4mt_LM.js → json-ChdEfB0X.js} +18 -35
- package/dist/model/-private.js +1 -1
- package/dist/model/migration-support.js +59 -27
- package/dist/model-for-CqXsIKws.js +221 -0
- package/dist/model-fragments.js +76 -0
- package/dist/model.js +18 -90
- package/dist/{schema-provider-DQu4Rjco.js → schema-provider-DJCV_6AF.js} +50 -95
- package/dist/{serialize-into-hash-CS0MIv4F.js → serialize-into-hash-DPZYoF-i.js} +1 -1
- package/dist/serializer/json-api.js +18 -45
- package/dist/serializer/json.js +1 -1
- package/dist/serializer/rest.js +14 -21
- package/dist/serializer/transform.js +15 -6
- package/dist/serializer.js +9 -13
- package/dist/store.js +5 -1
- package/dist/unpkg/dev/-private-DtjBbEgy.js +1206 -0
- package/dist/unpkg/dev/adapter/-private.js +1 -0
- package/dist/unpkg/dev/adapter/error.js +335 -0
- package/dist/unpkg/dev/adapter/json-api.js +271 -0
- package/dist/unpkg/dev/adapter/rest.js +1171 -0
- package/dist/unpkg/dev/adapter.js +1252 -0
- package/dist/unpkg/dev/compat/-private.js +1 -0
- package/dist/unpkg/dev/compat/builders.js +275 -0
- package/dist/unpkg/dev/compat/extensions.js +242 -0
- package/dist/unpkg/dev/compat/utils.js +223 -0
- package/dist/unpkg/dev/compat.js +1147 -0
- package/dist/unpkg/dev/errors-DmGGJr3T.js +2562 -0
- package/dist/unpkg/dev/hooks-CkYiE6Ud.js +73 -0
- package/dist/unpkg/dev/index.js +197 -0
- package/dist/unpkg/dev/json-Cu1LNgmQ.js +1256 -0
- package/dist/unpkg/dev/model/-private.js +1 -0
- package/dist/unpkg/dev/model/migration-support.js +553 -0
- package/dist/unpkg/dev/model-for-CqXsIKws.js +221 -0
- package/dist/unpkg/dev/model-fragments.js +76 -0
- package/dist/unpkg/dev/model.js +678 -0
- package/dist/unpkg/dev/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
- package/dist/unpkg/dev/schema-provider-DDVYxmUV.js +2186 -0
- package/dist/unpkg/dev/serialize-into-hash-B2xDbuo5.js +259 -0
- package/dist/unpkg/dev/serializer/json-api.js +649 -0
- package/dist/unpkg/dev/serializer/json.js +4 -0
- package/dist/unpkg/dev/serializer/rest.js +1242 -0
- package/dist/unpkg/dev/serializer/transform.js +278 -0
- package/dist/unpkg/dev/serializer.js +248 -0
- package/dist/unpkg/dev/store.js +637 -0
- package/dist/unpkg/dev/util-DvanW33H.js +20 -0
- package/dist/unpkg/dev/utils-BhvS1iTS.js +8 -0
- package/dist/unpkg/dev-deprecated/-private-DtjBbEgy.js +1206 -0
- package/dist/unpkg/dev-deprecated/adapter/-private.js +1 -0
- package/dist/unpkg/dev-deprecated/adapter/error.js +335 -0
- package/dist/unpkg/dev-deprecated/adapter/json-api.js +271 -0
- package/dist/unpkg/dev-deprecated/adapter/rest.js +1171 -0
- package/dist/unpkg/dev-deprecated/adapter.js +1252 -0
- package/dist/unpkg/dev-deprecated/compat/-private.js +1 -0
- package/dist/unpkg/dev-deprecated/compat/builders.js +275 -0
- package/dist/unpkg/dev-deprecated/compat/extensions.js +242 -0
- package/dist/unpkg/dev-deprecated/compat/utils.js +223 -0
- package/dist/unpkg/dev-deprecated/compat.js +1147 -0
- package/dist/unpkg/dev-deprecated/errors-Spt6ubMd.js +2565 -0
- package/dist/unpkg/dev-deprecated/hooks-DOXegvhL.js +73 -0
- package/dist/unpkg/dev-deprecated/index.js +196 -0
- package/dist/unpkg/dev-deprecated/json-Cu1LNgmQ.js +1256 -0
- package/dist/unpkg/dev-deprecated/model/-private.js +1 -0
- package/dist/unpkg/dev-deprecated/model/migration-support.js +570 -0
- package/dist/unpkg/dev-deprecated/model-for-CqXsIKws.js +221 -0
- package/dist/unpkg/dev-deprecated/model-fragments.js +76 -0
- package/dist/unpkg/dev-deprecated/model.js +682 -0
- package/dist/unpkg/dev-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
- package/dist/unpkg/dev-deprecated/schema-provider-BP6_8N-V.js +2211 -0
- package/dist/unpkg/dev-deprecated/serialize-into-hash-B2xDbuo5.js +259 -0
- package/dist/unpkg/dev-deprecated/serializer/json-api.js +649 -0
- package/dist/unpkg/dev-deprecated/serializer/json.js +4 -0
- package/dist/unpkg/dev-deprecated/serializer/rest.js +1242 -0
- package/dist/unpkg/dev-deprecated/serializer/transform.js +278 -0
- package/dist/unpkg/dev-deprecated/serializer.js +248 -0
- package/dist/unpkg/dev-deprecated/store.js +637 -0
- package/dist/unpkg/dev-deprecated/util-CWr5WQOT.js +24 -0
- package/dist/unpkg/dev-deprecated/utils-C9PJehtL.js +12 -0
- package/dist/unpkg/prod/-private-BdyZaGEh.js +971 -0
- package/dist/unpkg/prod/adapter/-private.js +1 -0
- package/dist/unpkg/prod/adapter/error.js +330 -0
- package/dist/unpkg/prod/adapter/json-api.js +266 -0
- package/dist/unpkg/prod/adapter/rest.js +1134 -0
- package/dist/unpkg/prod/adapter.js +1219 -0
- package/dist/unpkg/prod/compat/-private.js +1 -0
- package/dist/unpkg/prod/compat/builders.js +210 -0
- package/dist/unpkg/prod/compat/extensions.js +232 -0
- package/dist/unpkg/prod/compat/utils.js +218 -0
- package/dist/unpkg/prod/compat.js +727 -0
- package/dist/unpkg/prod/errors-BGVFCBmi.js +2314 -0
- package/dist/unpkg/prod/hooks-BztVA_x0.js +41 -0
- package/dist/unpkg/prod/index.js +151 -0
- package/dist/unpkg/prod/json-BWrZ5546.js +1243 -0
- package/dist/unpkg/prod/model/-private.js +1 -0
- package/dist/unpkg/prod/model/migration-support.js +546 -0
- package/dist/unpkg/prod/model-for-CqXsIKws.js +221 -0
- package/dist/unpkg/prod/model-fragments.js +76 -0
- package/dist/unpkg/prod/model.js +593 -0
- package/dist/unpkg/prod/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
- package/dist/unpkg/prod/schema-provider-DJtD_8jZ.js +1861 -0
- package/dist/unpkg/prod/serialize-into-hash-DGlzQteF.js +215 -0
- package/dist/unpkg/prod/serializer/json-api.js +592 -0
- package/dist/unpkg/prod/serializer/json.js +4 -0
- package/dist/unpkg/prod/serializer/rest.js +1210 -0
- package/dist/unpkg/prod/serializer/transform.js +278 -0
- package/dist/unpkg/prod/serializer.js +248 -0
- package/dist/unpkg/prod/store.js +505 -0
- package/dist/unpkg/prod/util-DvanW33H.js +20 -0
- package/dist/unpkg/prod/utils-BhvS1iTS.js +8 -0
- package/dist/unpkg/prod-deprecated/-private-BdyZaGEh.js +971 -0
- package/dist/unpkg/prod-deprecated/adapter/-private.js +1 -0
- package/dist/unpkg/prod-deprecated/adapter/error.js +330 -0
- package/dist/unpkg/prod-deprecated/adapter/json-api.js +266 -0
- package/dist/unpkg/prod-deprecated/adapter/rest.js +1134 -0
- package/dist/unpkg/prod-deprecated/adapter.js +1219 -0
- package/dist/unpkg/prod-deprecated/compat/-private.js +1 -0
- package/dist/unpkg/prod-deprecated/compat/builders.js +210 -0
- package/dist/unpkg/prod-deprecated/compat/extensions.js +232 -0
- package/dist/unpkg/prod-deprecated/compat/utils.js +218 -0
- package/dist/unpkg/prod-deprecated/compat.js +727 -0
- package/dist/unpkg/prod-deprecated/errors-CdDaK81x.js +2317 -0
- package/dist/unpkg/prod-deprecated/hooks-yId87yyG.js +41 -0
- package/dist/unpkg/prod-deprecated/index.js +150 -0
- package/dist/unpkg/prod-deprecated/json-BWrZ5546.js +1243 -0
- package/dist/unpkg/prod-deprecated/model/-private.js +1 -0
- package/dist/unpkg/prod-deprecated/model/migration-support.js +563 -0
- package/dist/unpkg/prod-deprecated/model-for-CqXsIKws.js +221 -0
- package/dist/unpkg/prod-deprecated/model-fragments.js +76 -0
- package/dist/unpkg/prod-deprecated/model.js +596 -0
- package/dist/unpkg/prod-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
- package/dist/unpkg/prod-deprecated/schema-provider-CjX55uSY.js +1904 -0
- package/dist/unpkg/prod-deprecated/serialize-into-hash-DGlzQteF.js +215 -0
- package/dist/unpkg/prod-deprecated/serializer/json-api.js +592 -0
- package/dist/unpkg/prod-deprecated/serializer/json.js +4 -0
- package/dist/unpkg/prod-deprecated/serializer/rest.js +1210 -0
- package/dist/unpkg/prod-deprecated/serializer/transform.js +278 -0
- package/dist/unpkg/prod-deprecated/serializer.js +248 -0
- package/dist/unpkg/prod-deprecated/store.js +505 -0
- package/dist/unpkg/prod-deprecated/util-B6cn-i93.js +23 -0
- package/dist/unpkg/prod-deprecated/utils-BUWwQwCh.js +11 -0
- package/logos/README.md +2 -2
- package/logos/logo-yellow-slab.svg +1 -0
- package/logos/word-mark-black.svg +1 -0
- package/logos/word-mark-white.svg +1 -0
- package/package.json +15 -7
- package/logos/NCC-1701-a-blue.svg +0 -4
- package/logos/NCC-1701-a-gold.svg +0 -4
- package/logos/NCC-1701-a-gold_100.svg +0 -1
- package/logos/NCC-1701-a-gold_base-64.txt +0 -1
- package/logos/NCC-1701-a.svg +0 -4
- package/logos/docs-badge.svg +0 -2
- package/logos/ember-data-logo-dark.svg +0 -12
- package/logos/ember-data-logo-light.svg +0 -12
- package/logos/social1.png +0 -0
- package/logos/social2.png +0 -0
- package/logos/warp-drive-logo-dark.svg +0 -4
- package/logos/warp-drive-logo-gold.svg +0 -4
|
@@ -0,0 +1,1242 @@
|
|
|
1
|
+
import { camelize, dasherize, singularize } from '@warp-drive/utilities/string';
|
|
2
|
+
import { J as JSONSerializer, c as coerceId } from "../json-Cu1LNgmQ.js";
|
|
3
|
+
import Mixin from '@ember/object/mixin';
|
|
4
|
+
|
|
5
|
+
/* eslint-disable @typescript-eslint/no-unsafe-argument */
|
|
6
|
+
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
|
7
|
+
/* eslint-disable @typescript-eslint/no-unsafe-call */
|
|
8
|
+
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
|
9
|
+
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
## Using Embedded Records
|
|
13
|
+
|
|
14
|
+
`EmbeddedRecordsMixin` supports serializing embedded records.
|
|
15
|
+
|
|
16
|
+
To set up embedded records, include the mixin when extending a serializer,
|
|
17
|
+
then define and configure embedded (model) relationships.
|
|
18
|
+
|
|
19
|
+
Note that embedded records will serialize with the serializer for their model instead of the serializer in which they are defined.
|
|
20
|
+
|
|
21
|
+
Note also that this mixin does not work with JSONAPISerializer because the JSON:API specification does not describe how to format embedded resources.
|
|
22
|
+
|
|
23
|
+
Below is an example of a per-type serializer (`post` type).
|
|
24
|
+
|
|
25
|
+
```js [app/serializers/post.js]
|
|
26
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@warp-drive/legacy/serializer/rest';
|
|
27
|
+
|
|
28
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
29
|
+
attrs = {
|
|
30
|
+
author: { embedded: 'always' },
|
|
31
|
+
comments: { serialize: 'ids' }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
Note that this use of `{ embedded: 'always' }` is unrelated to
|
|
36
|
+
the `{ embedded: 'always' }` that is defined as an option on `attr` as part of
|
|
37
|
+
defining a model while working with the `ActiveModelSerializer`. Nevertheless,
|
|
38
|
+
using `{ embedded: 'always' }` as an option to `attr` is not a valid way to set up
|
|
39
|
+
embedded records.
|
|
40
|
+
|
|
41
|
+
The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
{
|
|
45
|
+
serialize: 'records',
|
|
46
|
+
deserialize: 'records'
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Configuring Attrs
|
|
51
|
+
|
|
52
|
+
A resource's `attrs` option may be set to use `ids`, `records` or false for the
|
|
53
|
+
`serialize` and `deserialize` settings.
|
|
54
|
+
|
|
55
|
+
The `attrs` property can be set on the `ApplicationSerializer` or a per-type
|
|
56
|
+
serializer.
|
|
57
|
+
|
|
58
|
+
In the case where embedded JSON is expected while extracting a payload (reading)
|
|
59
|
+
the setting is `deserialize: 'records'`, there is no need to use `ids` when
|
|
60
|
+
extracting as that is the default behaviour without this mixin if you are using
|
|
61
|
+
the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while
|
|
62
|
+
serializing `serialize: 'records'` is the setting to use. There is an option of
|
|
63
|
+
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
|
|
64
|
+
do not want the relationship sent at all, you can use `serialize: false`.
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
### EmbeddedRecordsMixin defaults
|
|
68
|
+
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
|
|
69
|
+
will behave in the following way:
|
|
70
|
+
|
|
71
|
+
BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
|
|
72
|
+
HasMany: `{ serialize: false, deserialize: 'ids' }`
|
|
73
|
+
|
|
74
|
+
### Model Relationships
|
|
75
|
+
|
|
76
|
+
Embedded records must have a model defined to be extracted and serialized. Note that
|
|
77
|
+
when defining any relationships on your model such as `belongsTo` and `hasMany`, you
|
|
78
|
+
should not both specify `async: true` and also indicate through the serializer's
|
|
79
|
+
`attrs` attribute that the related model should be embedded for deserialization.
|
|
80
|
+
If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`),
|
|
81
|
+
then do not use `async: true`.
|
|
82
|
+
|
|
83
|
+
To successfully extract and serialize embedded records the model relationships
|
|
84
|
+
must be set up correctly. See the
|
|
85
|
+
[defining relationships](https://guides.emberjs.com/current/models/relationships)
|
|
86
|
+
section of the **Defining Models** guide page.
|
|
87
|
+
|
|
88
|
+
Records without an `id` property are not considered embedded records, model
|
|
89
|
+
instances must have an `id` property to be used with Ember Data.
|
|
90
|
+
|
|
91
|
+
### Example JSON payloads, Models and Serializers
|
|
92
|
+
|
|
93
|
+
**When customizing a serializer it is important to grok what the customizations
|
|
94
|
+
are. Please read the docs for the methods this mixin provides, in case you need
|
|
95
|
+
to modify it to fit your specific needs.**
|
|
96
|
+
|
|
97
|
+
@class EmbeddedRecordsMixin
|
|
98
|
+
@public
|
|
99
|
+
*/
|
|
100
|
+
const EmbeddedRecordsMixin = Mixin.create({
|
|
101
|
+
/**
|
|
102
|
+
Normalize the record and recursively normalize/extract all the embedded records
|
|
103
|
+
while pushing them into the store as they are encountered
|
|
104
|
+
A payload with an attr configured for embedded records needs to be extracted:
|
|
105
|
+
```js
|
|
106
|
+
{
|
|
107
|
+
"post": {
|
|
108
|
+
"id": "1"
|
|
109
|
+
"title": "Rails is omakase",
|
|
110
|
+
"comments": [{
|
|
111
|
+
"id": "1",
|
|
112
|
+
"body": "Rails is unagi"
|
|
113
|
+
}, {
|
|
114
|
+
"id": "2",
|
|
115
|
+
"body": "Omakase O_o"
|
|
116
|
+
}]
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
@public
|
|
121
|
+
@param {Model} typeClass
|
|
122
|
+
@param {Object} hash to be normalized
|
|
123
|
+
@param {String} prop the hash has been referenced by
|
|
124
|
+
@return {Object} the normalized hash
|
|
125
|
+
**/
|
|
126
|
+
normalize(typeClass, hash, prop) {
|
|
127
|
+
const normalizedHash = this._super(typeClass, hash, prop);
|
|
128
|
+
return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash);
|
|
129
|
+
},
|
|
130
|
+
keyForRelationship(key, typeClass, method) {
|
|
131
|
+
if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) {
|
|
132
|
+
return this.keyForAttribute(key, method);
|
|
133
|
+
} else {
|
|
134
|
+
return this._super(key, typeClass, method) || key;
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
/**
|
|
138
|
+
Serialize `belongsTo` relationship when it is configured as an embedded object.
|
|
139
|
+
This example of an author model belongs to a post model:
|
|
140
|
+
```js
|
|
141
|
+
import Model, { attr, belongsTo } from '@warp-drive/legacy/model';
|
|
142
|
+
Post = Model.extend({
|
|
143
|
+
title: attr('string'),
|
|
144
|
+
body: attr('string'),
|
|
145
|
+
author: belongsTo('author')
|
|
146
|
+
});
|
|
147
|
+
Author = Model.extend({
|
|
148
|
+
name: attr('string'),
|
|
149
|
+
post: belongsTo('post')
|
|
150
|
+
});
|
|
151
|
+
```
|
|
152
|
+
Use a custom (type) serializer for the post model to configure embedded author
|
|
153
|
+
```js [app/serializers/post.js]
|
|
154
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@warp-drive/legacy/serializer/rest';
|
|
155
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
156
|
+
attrs = {
|
|
157
|
+
author: { embedded: 'always' }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
A payload with an attribute configured for embedded records can serialize
|
|
162
|
+
the records together under the root attribute's payload:
|
|
163
|
+
```js
|
|
164
|
+
{
|
|
165
|
+
"post": {
|
|
166
|
+
"id": "1"
|
|
167
|
+
"title": "Rails is omakase",
|
|
168
|
+
"author": {
|
|
169
|
+
"id": "2"
|
|
170
|
+
"name": "dhh"
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
@public
|
|
176
|
+
@param {Snapshot} snapshot
|
|
177
|
+
@param {Object} json
|
|
178
|
+
@param {Object} relationship
|
|
179
|
+
*/
|
|
180
|
+
serializeBelongsTo(snapshot, json, relationship) {
|
|
181
|
+
const attr = relationship.name;
|
|
182
|
+
if (this.noSerializeOptionSpecified(attr)) {
|
|
183
|
+
this._super(snapshot, json, relationship);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const includeIds = this.hasSerializeIdsOption(attr);
|
|
187
|
+
const includeRecords = this.hasSerializeRecordsOption(attr);
|
|
188
|
+
const embeddedSnapshot = snapshot.belongsTo(attr);
|
|
189
|
+
if (includeIds) {
|
|
190
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
191
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
192
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
193
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
194
|
+
}
|
|
195
|
+
if (!embeddedSnapshot) {
|
|
196
|
+
json[serializedKey] = null;
|
|
197
|
+
} else {
|
|
198
|
+
json[serializedKey] = embeddedSnapshot.id;
|
|
199
|
+
if (relationship.options.polymorphic) {
|
|
200
|
+
this.serializePolymorphicType(snapshot, json, relationship);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
} else if (includeRecords) {
|
|
204
|
+
this._serializeEmbeddedBelongsTo(snapshot, json, relationship);
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
_serializeEmbeddedBelongsTo(snapshot, json, relationship) {
|
|
208
|
+
const embeddedSnapshot = snapshot.belongsTo(relationship.name);
|
|
209
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
210
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
211
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
212
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
213
|
+
}
|
|
214
|
+
if (!embeddedSnapshot) {
|
|
215
|
+
json[serializedKey] = null;
|
|
216
|
+
} else {
|
|
217
|
+
json[serializedKey] = embeddedSnapshot.serialize({
|
|
218
|
+
includeId: true
|
|
219
|
+
});
|
|
220
|
+
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]);
|
|
221
|
+
if (relationship.options.polymorphic) {
|
|
222
|
+
this.serializePolymorphicType(snapshot, json, relationship);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
/**
|
|
227
|
+
Serializes `hasMany` relationships when it is configured as embedded objects.
|
|
228
|
+
This example of a post model has many comments:
|
|
229
|
+
```js
|
|
230
|
+
import Model, { attr, belongsTo, hasMany } from '@warp-drive/legacy/model';
|
|
231
|
+
Post = Model.extend({
|
|
232
|
+
title: attr('string'),
|
|
233
|
+
body: attr('string'),
|
|
234
|
+
comments: hasMany('comment')
|
|
235
|
+
});
|
|
236
|
+
Comment = Model.extend({
|
|
237
|
+
body: attr('string'),
|
|
238
|
+
post: belongsTo('post')
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
Use a custom (type) serializer for the post model to configure embedded comments
|
|
242
|
+
```js [app/serializers/post.js]
|
|
243
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@warp-drive/legacy/serializer/rest';
|
|
244
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
245
|
+
attrs = {
|
|
246
|
+
comments: { embedded: 'always' }
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
A payload with an attribute configured for embedded records can serialize
|
|
251
|
+
the records together under the root attribute's payload:
|
|
252
|
+
```js
|
|
253
|
+
{
|
|
254
|
+
"post": {
|
|
255
|
+
"id": "1"
|
|
256
|
+
"title": "Rails is omakase",
|
|
257
|
+
"body": "I want this for my ORM, I want that for my template language..."
|
|
258
|
+
"comments": [{
|
|
259
|
+
"id": "1",
|
|
260
|
+
"body": "Rails is unagi"
|
|
261
|
+
}, {
|
|
262
|
+
"id": "2",
|
|
263
|
+
"body": "Omakase O_o"
|
|
264
|
+
}]
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
The attrs options object can use more specific instruction for extracting and
|
|
269
|
+
serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set.
|
|
270
|
+
When extracting the only option is `records`.
|
|
271
|
+
So `{ embedded: 'always' }` is shorthand for:
|
|
272
|
+
`{ serialize: 'records', deserialize: 'records' }`
|
|
273
|
+
To embed the `ids` for a related object (using a hasMany relationship):
|
|
274
|
+
```js [app/serializers/post.js]
|
|
275
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@warp-drive/legacy/serializer/rest';
|
|
276
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
277
|
+
attrs = {
|
|
278
|
+
comments: { serialize: 'ids', deserialize: 'records' }
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
```js
|
|
283
|
+
{
|
|
284
|
+
"post": {
|
|
285
|
+
"id": "1"
|
|
286
|
+
"title": "Rails is omakase",
|
|
287
|
+
"body": "I want this for my ORM, I want that for my template language..."
|
|
288
|
+
"comments": ["1", "2"]
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
To embed the relationship as a collection of objects with `id` and `type` keys, set
|
|
293
|
+
`ids-and-types` for the related object.
|
|
294
|
+
This is particularly useful for polymorphic relationships where records don't share
|
|
295
|
+
the same table and the `id` is not enough information.
|
|
296
|
+
For example having a user that has many pets:
|
|
297
|
+
```js
|
|
298
|
+
User = Model.extend({
|
|
299
|
+
name: attr('string'),
|
|
300
|
+
pets: hasMany('pet', { polymorphic: true })
|
|
301
|
+
});
|
|
302
|
+
Pet = Model.extend({
|
|
303
|
+
name: attr('string'),
|
|
304
|
+
});
|
|
305
|
+
Cat = Pet.extend({
|
|
306
|
+
// ...
|
|
307
|
+
});
|
|
308
|
+
Parrot = Pet.extend({
|
|
309
|
+
// ...
|
|
310
|
+
});
|
|
311
|
+
```
|
|
312
|
+
```js [app/serializers/user.js]
|
|
313
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@warp-drive/legacy/serializer/rest';
|
|
314
|
+
export default class UserSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
315
|
+
attrs = {
|
|
316
|
+
pets: { serialize: 'ids-and-types', deserialize: 'records' }
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
```js
|
|
321
|
+
{
|
|
322
|
+
"user": {
|
|
323
|
+
"id": "1"
|
|
324
|
+
"name": "Bertin Osborne",
|
|
325
|
+
"pets": [
|
|
326
|
+
{ "id": "1", "type": "Cat" },
|
|
327
|
+
{ "id": "1", "type": "Parrot"}
|
|
328
|
+
]
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
```
|
|
332
|
+
@public
|
|
333
|
+
@param {Snapshot} snapshot
|
|
334
|
+
@param {Object} json
|
|
335
|
+
@param {Object} relationship
|
|
336
|
+
*/
|
|
337
|
+
serializeHasMany(snapshot, json, relationship) {
|
|
338
|
+
const attr = relationship.name;
|
|
339
|
+
if (this.noSerializeOptionSpecified(attr)) {
|
|
340
|
+
this._super(snapshot, json, relationship);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (this.hasSerializeIdsOption(attr)) {
|
|
344
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
345
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
346
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
347
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
348
|
+
}
|
|
349
|
+
json[serializedKey] = snapshot.hasMany(attr, {
|
|
350
|
+
ids: true
|
|
351
|
+
});
|
|
352
|
+
} else if (this.hasSerializeRecordsOption(attr)) {
|
|
353
|
+
this._serializeEmbeddedHasMany(snapshot, json, relationship);
|
|
354
|
+
} else {
|
|
355
|
+
if (this.hasSerializeIdsAndTypesOption(attr)) {
|
|
356
|
+
this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
/*
|
|
361
|
+
Serializes a hasMany relationship as an array of objects containing only `id` and `type`
|
|
362
|
+
keys.
|
|
363
|
+
This has its use case on polymorphic hasMany relationships where the server is not storing
|
|
364
|
+
all records in the same table using STI, and therefore the `id` is not enough information
|
|
365
|
+
TODO: Make the default in Ember-data 3.0??
|
|
366
|
+
*/
|
|
367
|
+
_serializeHasManyAsIdsAndTypes(snapshot, json, relationship) {
|
|
368
|
+
const serializedKey = this.keyForAttribute(relationship.name, 'serialize');
|
|
369
|
+
const hasMany = snapshot.hasMany(relationship.name) || [];
|
|
370
|
+
json[serializedKey] = hasMany.map(function (recordSnapshot) {
|
|
371
|
+
//
|
|
372
|
+
// I'm sure I'm being utterly naive here. Probably id is a configurable property and
|
|
373
|
+
// type too, and the modelName has to be normalized somehow.
|
|
374
|
+
//
|
|
375
|
+
return {
|
|
376
|
+
id: recordSnapshot.id,
|
|
377
|
+
type: recordSnapshot.modelName
|
|
378
|
+
};
|
|
379
|
+
});
|
|
380
|
+
},
|
|
381
|
+
_serializeEmbeddedHasMany(snapshot, json, relationship) {
|
|
382
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
383
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
384
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
385
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
386
|
+
}
|
|
387
|
+
console.warn(`The embedded relationship '${serializedKey}' is undefined for '${snapshot.modelName}' with id '${snapshot.id}'. Please include it in your original payload.`, typeof snapshot.hasMany(relationship.name) !== 'undefined', {
|
|
388
|
+
id: 'ds.serializer.embedded-relationship-undefined'
|
|
389
|
+
});
|
|
390
|
+
json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship);
|
|
391
|
+
},
|
|
392
|
+
/*
|
|
393
|
+
Returns an array of embedded records serialized to JSON
|
|
394
|
+
*/
|
|
395
|
+
_generateSerializedHasMany(snapshot, relationship) {
|
|
396
|
+
const hasMany = snapshot.hasMany(relationship.name) || [];
|
|
397
|
+
const ret = new Array(hasMany.length);
|
|
398
|
+
for (let i = 0; i < hasMany.length; i++) {
|
|
399
|
+
const embeddedSnapshot = hasMany[i];
|
|
400
|
+
const embeddedJson = embeddedSnapshot.serialize({
|
|
401
|
+
includeId: true
|
|
402
|
+
});
|
|
403
|
+
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
|
|
404
|
+
ret[i] = embeddedJson;
|
|
405
|
+
}
|
|
406
|
+
return ret;
|
|
407
|
+
},
|
|
408
|
+
/**
|
|
409
|
+
When serializing an embedded record, modify the property (in the `JSON` payload)
|
|
410
|
+
that refers to the parent record (foreign key for the relationship).
|
|
411
|
+
Serializing a `belongsTo` relationship removes the property that refers to the
|
|
412
|
+
parent record
|
|
413
|
+
Serializing a `hasMany` relationship does not remove the property that refers to
|
|
414
|
+
the parent record.
|
|
415
|
+
@public
|
|
416
|
+
@param {Snapshot} snapshot
|
|
417
|
+
@param {Snapshot} embeddedSnapshot
|
|
418
|
+
@param {Object} relationship
|
|
419
|
+
@param {Object} json
|
|
420
|
+
*/
|
|
421
|
+
removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json) {
|
|
422
|
+
if (relationship.kind === 'belongsTo') {
|
|
423
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
424
|
+
const parentRecord = schema.inverseFor(relationship.name, this.store);
|
|
425
|
+
if (parentRecord) {
|
|
426
|
+
const name = parentRecord.name;
|
|
427
|
+
const embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName);
|
|
428
|
+
const parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize');
|
|
429
|
+
if (parentKey) {
|
|
430
|
+
delete json[parentKey];
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
} /*else if (relationship.kind === 'hasMany') {
|
|
434
|
+
return;
|
|
435
|
+
}*/
|
|
436
|
+
},
|
|
437
|
+
// checks config for attrs option to embedded (always) - serialize and deserialize
|
|
438
|
+
hasEmbeddedAlwaysOption(attr) {
|
|
439
|
+
const option = this.attrsOption(attr);
|
|
440
|
+
return option && option.embedded === 'always';
|
|
441
|
+
},
|
|
442
|
+
// checks config for attrs option to serialize ids
|
|
443
|
+
hasSerializeRecordsOption(attr) {
|
|
444
|
+
const alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
|
|
445
|
+
const option = this.attrsOption(attr);
|
|
446
|
+
return alwaysEmbed || option && option.serialize === 'records';
|
|
447
|
+
},
|
|
448
|
+
// checks config for attrs option to serialize records
|
|
449
|
+
hasSerializeIdsOption(attr) {
|
|
450
|
+
const option = this.attrsOption(attr);
|
|
451
|
+
return option && (option.serialize === 'ids' || option.serialize === 'id');
|
|
452
|
+
},
|
|
453
|
+
// checks config for attrs option to serialize records as objects containing id and types
|
|
454
|
+
hasSerializeIdsAndTypesOption(attr) {
|
|
455
|
+
const option = this.attrsOption(attr);
|
|
456
|
+
return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type');
|
|
457
|
+
},
|
|
458
|
+
// checks config for attrs option to serialize records
|
|
459
|
+
noSerializeOptionSpecified(attr) {
|
|
460
|
+
const option = this.attrsOption(attr);
|
|
461
|
+
return !(option && (option.serialize || option.embedded));
|
|
462
|
+
},
|
|
463
|
+
// checks config for attrs option to deserialize records
|
|
464
|
+
// a defined option object for a resource is treated the same as
|
|
465
|
+
// `deserialize: 'records'`
|
|
466
|
+
hasDeserializeRecordsOption(attr) {
|
|
467
|
+
const alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
|
|
468
|
+
const option = this.attrsOption(attr);
|
|
469
|
+
return alwaysEmbed || option && option.deserialize === 'records';
|
|
470
|
+
},
|
|
471
|
+
attrsOption(attr) {
|
|
472
|
+
const attrs = this.attrs;
|
|
473
|
+
return attrs && (attrs[camelize(attr)] || attrs[attr]);
|
|
474
|
+
},
|
|
475
|
+
/**
|
|
476
|
+
@private
|
|
477
|
+
*/
|
|
478
|
+
_extractEmbeddedRecords(serializer, store, typeClass, partial) {
|
|
479
|
+
typeClass.eachRelationship((key, relationship) => {
|
|
480
|
+
if (serializer.hasDeserializeRecordsOption(key)) {
|
|
481
|
+
if (relationship.kind === 'hasMany') {
|
|
482
|
+
this._extractEmbeddedHasMany(store, key, partial, relationship);
|
|
483
|
+
}
|
|
484
|
+
if (relationship.kind === 'belongsTo') {
|
|
485
|
+
this._extractEmbeddedBelongsTo(store, key, partial, relationship);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
return partial;
|
|
490
|
+
},
|
|
491
|
+
/**
|
|
492
|
+
@private
|
|
493
|
+
*/
|
|
494
|
+
_extractEmbeddedHasMany(store, key, hash, relationshipMeta) {
|
|
495
|
+
const relationshipHash = hash.data?.relationships?.[key]?.data;
|
|
496
|
+
if (!relationshipHash) {
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const hasMany = new Array(relationshipHash.length);
|
|
500
|
+
for (let i = 0; i < relationshipHash.length; i++) {
|
|
501
|
+
const item = relationshipHash[i];
|
|
502
|
+
const {
|
|
503
|
+
data,
|
|
504
|
+
included
|
|
505
|
+
} = this._normalizeEmbeddedRelationship(store, relationshipMeta, item);
|
|
506
|
+
hash.included = hash.included || [];
|
|
507
|
+
hash.included.push(data);
|
|
508
|
+
if (included) {
|
|
509
|
+
hash.included = hash.included.concat(included);
|
|
510
|
+
}
|
|
511
|
+
hasMany[i] = {
|
|
512
|
+
id: data.id,
|
|
513
|
+
type: data.type
|
|
514
|
+
};
|
|
515
|
+
if (data.lid) {
|
|
516
|
+
hasMany[i].lid = data.lid;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
const relationship = {
|
|
520
|
+
data: hasMany
|
|
521
|
+
};
|
|
522
|
+
hash.data.relationships[key] = relationship;
|
|
523
|
+
},
|
|
524
|
+
/**
|
|
525
|
+
@private
|
|
526
|
+
*/
|
|
527
|
+
_extractEmbeddedBelongsTo(store, key, hash, relationshipMeta) {
|
|
528
|
+
const relationshipHash = hash.data?.relationships?.[key]?.data;
|
|
529
|
+
if (!relationshipHash) {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const {
|
|
533
|
+
data,
|
|
534
|
+
included
|
|
535
|
+
} = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash);
|
|
536
|
+
hash.included = hash.included || [];
|
|
537
|
+
hash.included.push(data);
|
|
538
|
+
if (included) {
|
|
539
|
+
hash.included = hash.included.concat(included);
|
|
540
|
+
}
|
|
541
|
+
const belongsTo = {
|
|
542
|
+
id: data.id,
|
|
543
|
+
type: data.type
|
|
544
|
+
};
|
|
545
|
+
const relationship = {
|
|
546
|
+
data: belongsTo
|
|
547
|
+
};
|
|
548
|
+
if (data.lid) {
|
|
549
|
+
// @ts-expect-error
|
|
550
|
+
belongsTo.lid = data.lid;
|
|
551
|
+
}
|
|
552
|
+
hash.data.relationships[key] = relationship;
|
|
553
|
+
},
|
|
554
|
+
/**
|
|
555
|
+
@private
|
|
556
|
+
*/
|
|
557
|
+
_normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash) {
|
|
558
|
+
let modelName = relationshipMeta.type;
|
|
559
|
+
if (relationshipMeta.options.polymorphic) {
|
|
560
|
+
modelName = relationshipHash.type;
|
|
561
|
+
}
|
|
562
|
+
const modelClass = store.modelFor(modelName);
|
|
563
|
+
const serializer = store.serializerFor(modelName);
|
|
564
|
+
return serializer.normalize(modelClass, relationshipHash, null);
|
|
565
|
+
},
|
|
566
|
+
isEmbeddedRecordsMixin: true
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
/* eslint-disable @typescript-eslint/no-unsafe-argument */
|
|
570
|
+
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
|
571
|
+
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
|
572
|
+
/* eslint-disable @typescript-eslint/no-unsafe-call */
|
|
573
|
+
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
|
574
|
+
|
|
575
|
+
function makeArray(value) {
|
|
576
|
+
return Array.isArray(value) ? value : [value];
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* :::danger
|
|
581
|
+
⚠️ **This is LEGACY documentation** for a feature that is no longer encouraged to be used.
|
|
582
|
+
If starting a new app or thinking of implementing a new adapter, consider writing a
|
|
583
|
+
{@link Handler} instead to be used with the {@link RequestManager}
|
|
584
|
+
:::
|
|
585
|
+
|
|
586
|
+
Normally, applications will use the `RESTSerializer` by implementing
|
|
587
|
+
the `normalize` method.
|
|
588
|
+
|
|
589
|
+
This allows you to do whatever kind of munging you need and is
|
|
590
|
+
especially useful if your server is inconsistent and you need to
|
|
591
|
+
do munging differently for many different kinds of responses.
|
|
592
|
+
|
|
593
|
+
See the `normalize` documentation for more information.
|
|
594
|
+
|
|
595
|
+
## Across the Board Normalization
|
|
596
|
+
|
|
597
|
+
There are also a number of hooks that you might find useful to define
|
|
598
|
+
across-the-board rules for your payload. These rules will be useful
|
|
599
|
+
if your server is consistent, or if you're building an adapter for
|
|
600
|
+
an infrastructure service, like Firebase, and want to encode service
|
|
601
|
+
conventions.
|
|
602
|
+
|
|
603
|
+
For example, if all of your keys are underscored and all-caps, but
|
|
604
|
+
otherwise consistent with the names you use in your models, you
|
|
605
|
+
can implement across-the-board rules for how to convert an attribute
|
|
606
|
+
name in your model to a key in your JSON.
|
|
607
|
+
|
|
608
|
+
```js [app/serializers/application.js]
|
|
609
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
610
|
+
import { underscore } from '<app-name>/utils/string-utils';
|
|
611
|
+
|
|
612
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
613
|
+
keyForAttribute(attr, method) {
|
|
614
|
+
return underscore(attr).toUpperCase();
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
```
|
|
618
|
+
|
|
619
|
+
You can also implement `keyForRelationship`, which takes the name
|
|
620
|
+
of the relationship as the first parameter, the kind of
|
|
621
|
+
relationship (`hasMany` or `belongsTo`) as the second parameter, and
|
|
622
|
+
the method (`serialize` or `deserialize`) as the third parameter.
|
|
623
|
+
|
|
624
|
+
@class RESTSerializer
|
|
625
|
+
@public
|
|
626
|
+
*/
|
|
627
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
628
|
+
const RESTSerializer = JSONSerializer.extend({
|
|
629
|
+
/**
|
|
630
|
+
`keyForPolymorphicType` can be used to define a custom key when
|
|
631
|
+
serializing and deserializing a polymorphic type. By default, the
|
|
632
|
+
returned key is `${key}Type`.
|
|
633
|
+
Example
|
|
634
|
+
```js [app/serializers/post.js]
|
|
635
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
636
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
637
|
+
keyForPolymorphicType(key, relationship) {
|
|
638
|
+
let relationshipKey = this.keyForRelationship(key);
|
|
639
|
+
return 'type-' + relationshipKey;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
```
|
|
643
|
+
@public
|
|
644
|
+
*/
|
|
645
|
+
keyForPolymorphicType(key, type, method) {
|
|
646
|
+
// @ts-expect-error
|
|
647
|
+
const relationshipKey = this.keyForRelationship(key);
|
|
648
|
+
return `${relationshipKey}Type`;
|
|
649
|
+
},
|
|
650
|
+
/**
|
|
651
|
+
Normalizes a part of the JSON payload returned by
|
|
652
|
+
the server. You should override this method, munge the hash
|
|
653
|
+
and call super if you have generic normalization to do.
|
|
654
|
+
It takes the type of the record that is being normalized
|
|
655
|
+
(as a Model class), the property where the hash was
|
|
656
|
+
originally found, and the hash to normalize.
|
|
657
|
+
For example, if you have a payload that looks like this:
|
|
658
|
+
```js
|
|
659
|
+
{
|
|
660
|
+
"post": {
|
|
661
|
+
"id": 1,
|
|
662
|
+
"title": "Rails is omakase",
|
|
663
|
+
"comments": [ 1, 2 ]
|
|
664
|
+
},
|
|
665
|
+
"comments": [{
|
|
666
|
+
"id": 1,
|
|
667
|
+
"body": "FIRST"
|
|
668
|
+
}, {
|
|
669
|
+
"id": 2,
|
|
670
|
+
"body": "Rails is unagi"
|
|
671
|
+
}]
|
|
672
|
+
}
|
|
673
|
+
```
|
|
674
|
+
The `normalize` method will be called three times:
|
|
675
|
+
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
|
|
676
|
+
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
|
|
677
|
+
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
|
|
678
|
+
You can use this method, for example, to normalize underscored keys to camelized
|
|
679
|
+
or other general-purpose normalizations. You will only need to implement
|
|
680
|
+
`normalize` and manipulate the payload as desired.
|
|
681
|
+
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
|
|
682
|
+
`id`, you can specify how to normalize just the comments:
|
|
683
|
+
```js [app/serializers/post.js]
|
|
684
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
685
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
686
|
+
normalize(model, hash, prop) {
|
|
687
|
+
if (prop === 'comments') {
|
|
688
|
+
hash.id = hash._id;
|
|
689
|
+
delete hash._id;
|
|
690
|
+
}
|
|
691
|
+
return super.normalize(...arguments);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
```
|
|
695
|
+
On each call to the `normalize` method, the third parameter (`prop`) is always
|
|
696
|
+
one of the keys that were in the original payload or in the result of another
|
|
697
|
+
normalization as `normalizeResponse`.
|
|
698
|
+
@public
|
|
699
|
+
@param {Model} modelClass
|
|
700
|
+
@param {Object} resourceHash
|
|
701
|
+
@param {String} prop
|
|
702
|
+
@return {Object}
|
|
703
|
+
*/
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
Normalizes an array of resource payloads and returns a JSON-API Document
|
|
707
|
+
with primary data and, if any, included data as `{ data, included }`.
|
|
708
|
+
@private
|
|
709
|
+
*/
|
|
710
|
+
_normalizeArray(store, modelName, arrayHash, prop) {
|
|
711
|
+
const documentHash = {
|
|
712
|
+
data: [],
|
|
713
|
+
included: []
|
|
714
|
+
};
|
|
715
|
+
const modelClass = store.modelFor(modelName);
|
|
716
|
+
const serializer = store.serializerFor(modelName);
|
|
717
|
+
makeArray(arrayHash).forEach(hash => {
|
|
718
|
+
// @ts-expect-error
|
|
719
|
+
const {
|
|
720
|
+
data,
|
|
721
|
+
included
|
|
722
|
+
} = this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer);
|
|
723
|
+
// @ts-expect-error
|
|
724
|
+
documentHash.data.push(data);
|
|
725
|
+
if (included) {
|
|
726
|
+
documentHash.included = documentHash.included.concat(included);
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
return documentHash;
|
|
730
|
+
},
|
|
731
|
+
_normalizePolymorphicRecord(store, hash, prop, primaryModelClass, primarySerializer) {
|
|
732
|
+
let serializer = primarySerializer;
|
|
733
|
+
let modelClass = primaryModelClass;
|
|
734
|
+
const primaryHasTypeAttribute = primaryModelClass.fields.has('type');
|
|
735
|
+
|
|
736
|
+
// @ts-expect-error all the errors
|
|
737
|
+
if (!primaryHasTypeAttribute && hash.type) {
|
|
738
|
+
// Support polymorphic records in async relationships
|
|
739
|
+
// @ts-expect-error all the errors
|
|
740
|
+
const type = this.modelNameFromPayloadKey(hash.type);
|
|
741
|
+
if (store.schema.hasResource({
|
|
742
|
+
type
|
|
743
|
+
})) {
|
|
744
|
+
serializer = store.serializerFor(type);
|
|
745
|
+
modelClass = store.modelFor(type);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// @ts-expect-error all the errors
|
|
750
|
+
return serializer.normalize(modelClass, hash, prop);
|
|
751
|
+
},
|
|
752
|
+
/**
|
|
753
|
+
@private
|
|
754
|
+
*/
|
|
755
|
+
_normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) {
|
|
756
|
+
const documentHash = {
|
|
757
|
+
data: null,
|
|
758
|
+
included: []
|
|
759
|
+
};
|
|
760
|
+
// @ts-expect-error
|
|
761
|
+
const meta = this.extractMeta(store, primaryModelClass, payload);
|
|
762
|
+
if (meta) {
|
|
763
|
+
(test => {
|
|
764
|
+
if (!test) {
|
|
765
|
+
throw new Error('The `meta` returned from `extractMeta` has to be an object, not "' + typeof meta + '".');
|
|
766
|
+
}
|
|
767
|
+
})(typeof meta === 'object'); // @ts-expect-error
|
|
768
|
+
documentHash.meta = meta;
|
|
769
|
+
}
|
|
770
|
+
const keys = Object.keys(payload);
|
|
771
|
+
for (let i = 0, length = keys.length; i < length; i++) {
|
|
772
|
+
const prop = keys[i];
|
|
773
|
+
let modelName = prop;
|
|
774
|
+
let forcedSecondary = false;
|
|
775
|
+
|
|
776
|
+
/*
|
|
777
|
+
If you want to provide sideloaded records of the same type that the
|
|
778
|
+
primary data you can do that by prefixing the key with `_`.
|
|
779
|
+
Example
|
|
780
|
+
```
|
|
781
|
+
{
|
|
782
|
+
users: [
|
|
783
|
+
{ id: 1, title: 'Tom', manager: 3 },
|
|
784
|
+
{ id: 2, title: 'Yehuda', manager: 3 }
|
|
785
|
+
],
|
|
786
|
+
_users: [
|
|
787
|
+
{ id: 3, title: 'Tomster' }
|
|
788
|
+
]
|
|
789
|
+
}
|
|
790
|
+
```
|
|
791
|
+
This forces `_users` to be added to `included` instead of `data`.
|
|
792
|
+
*/
|
|
793
|
+
if (prop.charAt(0) === '_') {
|
|
794
|
+
forcedSecondary = true;
|
|
795
|
+
modelName = prop.substr(1);
|
|
796
|
+
}
|
|
797
|
+
const type = this.modelNameFromPayloadKey(modelName);
|
|
798
|
+
if (!store.schema.hasResource({
|
|
799
|
+
type
|
|
800
|
+
})) {
|
|
801
|
+
{
|
|
802
|
+
// @ts-expect-error
|
|
803
|
+
console.warn(this.warnMessageNoModelForKey(modelName, type), false, {
|
|
804
|
+
id: 'ds.serializer.model-for-key-missing'
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// eslint-disable-next-line no-var
|
|
811
|
+
var isPrimary = !forcedSecondary && this.isPrimaryType(store, type, primaryModelClass);
|
|
812
|
+
const value = payload[prop];
|
|
813
|
+
if (value === null) {
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
(test => {
|
|
817
|
+
if (!test) {
|
|
818
|
+
throw new Error('The adapter returned an array for the primary data of a `queryRecord` response. `queryRecord` should return a single record.');
|
|
819
|
+
}
|
|
820
|
+
})(!(requestType === 'queryRecord' && isPrimary && Array.isArray(value)));
|
|
821
|
+
|
|
822
|
+
/*
|
|
823
|
+
Support primary data as an object instead of an array.
|
|
824
|
+
Example
|
|
825
|
+
```
|
|
826
|
+
{
|
|
827
|
+
user: { id: 1, title: 'Tom', manager: 3 }
|
|
828
|
+
}
|
|
829
|
+
```
|
|
830
|
+
*/
|
|
831
|
+
if (isPrimary && !Array.isArray(value)) {
|
|
832
|
+
// @ts-expect-error
|
|
833
|
+
const {
|
|
834
|
+
data,
|
|
835
|
+
included
|
|
836
|
+
} = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this);
|
|
837
|
+
documentHash.data = data;
|
|
838
|
+
if (included) {
|
|
839
|
+
documentHash.included = documentHash.included.concat(included);
|
|
840
|
+
}
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
// @ts-expect-error
|
|
844
|
+
const {
|
|
845
|
+
data,
|
|
846
|
+
included
|
|
847
|
+
} = this._normalizeArray(store, type, value, prop);
|
|
848
|
+
if (included) {
|
|
849
|
+
documentHash.included = documentHash.included.concat(included);
|
|
850
|
+
}
|
|
851
|
+
if (isSingle) {
|
|
852
|
+
// eslint-disable-next-line @typescript-eslint/no-loop-func
|
|
853
|
+
data.forEach(resource => {
|
|
854
|
+
/*
|
|
855
|
+
Figures out if this is the primary record or not.
|
|
856
|
+
It's either:
|
|
857
|
+
1. The record with the same ID as the original request
|
|
858
|
+
2. If it's a newly created record without an ID, the first record
|
|
859
|
+
in the array
|
|
860
|
+
*/
|
|
861
|
+
const isUpdatedRecord = isPrimary && coerceId(resource.id) === id;
|
|
862
|
+
const isFirstCreatedRecord = isPrimary && !id && !documentHash.data;
|
|
863
|
+
if (isFirstCreatedRecord || isUpdatedRecord) {
|
|
864
|
+
documentHash.data = resource;
|
|
865
|
+
} else {
|
|
866
|
+
// @ts-expect-error
|
|
867
|
+
documentHash.included.push(resource);
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
} else {
|
|
871
|
+
if (isPrimary) {
|
|
872
|
+
documentHash.data = data;
|
|
873
|
+
} else {
|
|
874
|
+
if (data) {
|
|
875
|
+
documentHash.included = documentHash.included.concat(data);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
return documentHash;
|
|
881
|
+
},
|
|
882
|
+
isPrimaryType(store, modelName, primaryModelClass) {
|
|
883
|
+
return dasherize(modelName) === primaryModelClass.modelName;
|
|
884
|
+
},
|
|
885
|
+
/**
|
|
886
|
+
This method allows you to push a payload containing top-level
|
|
887
|
+
collections of records organized per type.
|
|
888
|
+
```js
|
|
889
|
+
{
|
|
890
|
+
"posts": [{
|
|
891
|
+
"id": "1",
|
|
892
|
+
"title": "Rails is omakase",
|
|
893
|
+
"author", "1",
|
|
894
|
+
"comments": [ "1" ]
|
|
895
|
+
}],
|
|
896
|
+
"comments": [{
|
|
897
|
+
"id": "1",
|
|
898
|
+
"body": "FIRST"
|
|
899
|
+
}],
|
|
900
|
+
"users": [{
|
|
901
|
+
"id": "1",
|
|
902
|
+
"name": "@d2h"
|
|
903
|
+
}]
|
|
904
|
+
}
|
|
905
|
+
```
|
|
906
|
+
It will first normalize the payload, so you can use this to push
|
|
907
|
+
in data streaming in from your server structured the same way
|
|
908
|
+
that fetches and saves are structured.
|
|
909
|
+
@public
|
|
910
|
+
*/
|
|
911
|
+
pushPayload(store, payload) {
|
|
912
|
+
const documentHash = {
|
|
913
|
+
data: [],
|
|
914
|
+
included: []
|
|
915
|
+
};
|
|
916
|
+
for (const prop in payload) {
|
|
917
|
+
const type = this.modelNameFromPayloadKey(prop);
|
|
918
|
+
if (!store.schema.hasResource({
|
|
919
|
+
type
|
|
920
|
+
})) {
|
|
921
|
+
{
|
|
922
|
+
// @ts-expect-error
|
|
923
|
+
console.warn(this.warnMessageNoModelForKey(prop, type), false, {
|
|
924
|
+
id: 'ds.serializer.model-for-key-missing'
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
const ModelSchema = store.modelFor(type);
|
|
930
|
+
const typeSerializer = store.serializerFor(ModelSchema.modelName);
|
|
931
|
+
makeArray(payload[prop]).forEach(hash => {
|
|
932
|
+
const {
|
|
933
|
+
data,
|
|
934
|
+
included
|
|
935
|
+
} = typeSerializer.normalize(ModelSchema, hash, prop);
|
|
936
|
+
// @ts-expect-error
|
|
937
|
+
documentHash.data.push(data);
|
|
938
|
+
if (included) {
|
|
939
|
+
documentHash.included = documentHash.included.concat(included);
|
|
940
|
+
}
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
store.push(documentHash);
|
|
944
|
+
},
|
|
945
|
+
/**
|
|
946
|
+
This method is used to convert each JSON root key in the payload
|
|
947
|
+
into a modelName that it can use to look up the appropriate model for
|
|
948
|
+
that part of the payload.
|
|
949
|
+
For example, your server may send a model name that does not correspond with
|
|
950
|
+
the name of the model in your app. Let's take a look at an example model,
|
|
951
|
+
and an example payload:
|
|
952
|
+
```js [app/models/post.js]
|
|
953
|
+
import Model from '@warp-drive/legacy/model';
|
|
954
|
+
export default class Post extends Model {}
|
|
955
|
+
```
|
|
956
|
+
```javascript
|
|
957
|
+
{
|
|
958
|
+
"blog/post": {
|
|
959
|
+
"id": "1
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
```
|
|
963
|
+
Ember Data is going to normalize the payload's root key for the modelName. As a result,
|
|
964
|
+
it will try to look up the "blog/post" model. Since we don't have a model called "blog/post"
|
|
965
|
+
(or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error
|
|
966
|
+
because it cannot find the "blog/post" model.
|
|
967
|
+
Since we want to remove this namespace, we can define a serializer for the application that will
|
|
968
|
+
remove "blog/" from the payload key whenver it's encountered by Ember Data:
|
|
969
|
+
```js [app/serializers/application.js]
|
|
970
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
971
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
972
|
+
modelNameFromPayloadKey(payloadKey) {
|
|
973
|
+
if (payloadKey === 'blog/post') {
|
|
974
|
+
return super.modelNameFromPayloadKey(payloadKey.replace('blog/', ''));
|
|
975
|
+
} else {
|
|
976
|
+
return super.modelNameFromPayloadKey(payloadKey);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
```
|
|
981
|
+
After refreshing, Ember Data will appropriately look up the "post" model.
|
|
982
|
+
By default the modelName for a model is its
|
|
983
|
+
name in dasherized form. This means that a payload key like "blogPost" would be
|
|
984
|
+
normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data
|
|
985
|
+
can use the correct inflection to do this for you. Most of the time, you won't
|
|
986
|
+
need to override `modelNameFromPayloadKey` for this purpose.
|
|
987
|
+
@public
|
|
988
|
+
@return the model's modelName
|
|
989
|
+
*/
|
|
990
|
+
modelNameFromPayloadKey(key) {
|
|
991
|
+
return dasherize(singularize(key));
|
|
992
|
+
},
|
|
993
|
+
// SERIALIZE
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
Called when a record is saved in order to convert the
|
|
997
|
+
record into JSON.
|
|
998
|
+
By default, it creates a JSON object with a key for
|
|
999
|
+
each attribute and belongsTo relationship.
|
|
1000
|
+
For example, consider this model:
|
|
1001
|
+
```js [app/models/comment.js]
|
|
1002
|
+
import Model, { attr, belongsTo } from '@warp-drive/legacy/model';
|
|
1003
|
+
export default class Comment extends Model {
|
|
1004
|
+
@attr title
|
|
1005
|
+
@attr body
|
|
1006
|
+
@belongsTo('user') author
|
|
1007
|
+
}
|
|
1008
|
+
```
|
|
1009
|
+
The default serialization would create a JSON object like:
|
|
1010
|
+
```js
|
|
1011
|
+
{
|
|
1012
|
+
"title": "Rails is unagi",
|
|
1013
|
+
"body": "Rails? Omakase? O_O",
|
|
1014
|
+
"author": 12
|
|
1015
|
+
}
|
|
1016
|
+
```
|
|
1017
|
+
By default, attributes are passed through as-is, unless
|
|
1018
|
+
you specified an attribute type (`attr('date')`). If
|
|
1019
|
+
you specify a transform, the JavaScript value will be
|
|
1020
|
+
serialized when inserted into the JSON hash.
|
|
1021
|
+
By default, belongs-to relationships are converted into
|
|
1022
|
+
IDs when inserted into the JSON hash.
|
|
1023
|
+
## IDs
|
|
1024
|
+
`serialize` takes an options hash with a single option:
|
|
1025
|
+
`includeId`. If this option is `true`, `serialize` will,
|
|
1026
|
+
by default include the ID in the JSON object it builds.
|
|
1027
|
+
The adapter passes in `includeId: true` when serializing
|
|
1028
|
+
a record for `createRecord`, but not for `updateRecord`.
|
|
1029
|
+
## Customization
|
|
1030
|
+
Your server may expect a different JSON format than the
|
|
1031
|
+
built-in serialization format.
|
|
1032
|
+
In that case, you can implement `serialize` yourself and
|
|
1033
|
+
return a JSON hash of your choosing.
|
|
1034
|
+
```js [app/serializers/post.js]
|
|
1035
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
1036
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
1037
|
+
serialize(snapshot, options) {
|
|
1038
|
+
let json = {
|
|
1039
|
+
POST_TTL: snapshot.attr('title'),
|
|
1040
|
+
POST_BDY: snapshot.attr('body'),
|
|
1041
|
+
POST_CMS: snapshot.hasMany('comments', { ids: true })
|
|
1042
|
+
};
|
|
1043
|
+
if (options.includeId) {
|
|
1044
|
+
json.POST_ID_ = snapshot.id;
|
|
1045
|
+
}
|
|
1046
|
+
return json;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
```
|
|
1050
|
+
## Customizing an App-Wide Serializer
|
|
1051
|
+
If you want to define a serializer for your entire
|
|
1052
|
+
application, you'll probably want to use `eachAttribute`
|
|
1053
|
+
and `eachRelationship` on the record.
|
|
1054
|
+
```js [app/serializers/application.js]
|
|
1055
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
1056
|
+
import { pluralize } from '<app-name>/utils/string-utils';
|
|
1057
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
1058
|
+
serialize(snapshot, options) {
|
|
1059
|
+
let json = {};
|
|
1060
|
+
snapshot.eachAttribute(function(name) {
|
|
1061
|
+
json[serverAttributeName(name)] = snapshot.attr(name);
|
|
1062
|
+
});
|
|
1063
|
+
snapshot.eachRelationship(function(name, relationship) {
|
|
1064
|
+
if (relationship.kind === 'hasMany') {
|
|
1065
|
+
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
|
|
1066
|
+
}
|
|
1067
|
+
});
|
|
1068
|
+
if (options.includeId) {
|
|
1069
|
+
json.ID_ = snapshot.id;
|
|
1070
|
+
}
|
|
1071
|
+
return json;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
function serverAttributeName(attribute) {
|
|
1075
|
+
return attribute.underscore().toUpperCase();
|
|
1076
|
+
}
|
|
1077
|
+
function serverHasManyName(name) {
|
|
1078
|
+
return serverAttributeName(singularize(name)) + "_IDS";
|
|
1079
|
+
}
|
|
1080
|
+
```
|
|
1081
|
+
This serializer will generate JSON that looks like this:
|
|
1082
|
+
```js
|
|
1083
|
+
{
|
|
1084
|
+
"TITLE": "Rails is omakase",
|
|
1085
|
+
"BODY": "Yep. Omakase.",
|
|
1086
|
+
"COMMENT_IDS": [ 1, 2, 3 ]
|
|
1087
|
+
}
|
|
1088
|
+
```
|
|
1089
|
+
## Tweaking the Default JSON
|
|
1090
|
+
If you just want to do some small tweaks on the default JSON,
|
|
1091
|
+
you can call super first and make the tweaks on the returned
|
|
1092
|
+
JSON.
|
|
1093
|
+
```js [app/serializers/post.js]
|
|
1094
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
1095
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
1096
|
+
serialize(snapshot, options) {
|
|
1097
|
+
let json = super.serialize(snapshot, options);
|
|
1098
|
+
json.subject = json.title;
|
|
1099
|
+
delete json.title;
|
|
1100
|
+
return json;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
```
|
|
1104
|
+
@public
|
|
1105
|
+
*/
|
|
1106
|
+
serialize(snapshot, options) {
|
|
1107
|
+
// @ts-expect-error
|
|
1108
|
+
return this._super(...arguments);
|
|
1109
|
+
},
|
|
1110
|
+
/**
|
|
1111
|
+
You can use this method to customize the root keys serialized into the JSON.
|
|
1112
|
+
The hash property should be modified by reference (possibly using something like _.extend)
|
|
1113
|
+
By default the REST Serializer sends the modelName of a model, which is a camelized
|
|
1114
|
+
version of the name.
|
|
1115
|
+
For example, your server may expect underscored root objects.
|
|
1116
|
+
```js [app/serializers/application.js]
|
|
1117
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
1118
|
+
import { underscore } from '<app-name>/utils/string-utils';
|
|
1119
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
1120
|
+
serializeIntoHash(data, type, record, options) {
|
|
1121
|
+
let root = underscore(type.modelName);
|
|
1122
|
+
data[root] = this.serialize(record, options);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
```
|
|
1126
|
+
@public
|
|
1127
|
+
*/
|
|
1128
|
+
serializeIntoHash(hash, typeClass, snapshot, options) {
|
|
1129
|
+
const normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName);
|
|
1130
|
+
hash[normalizedRootKey] = this.serialize(snapshot, options);
|
|
1131
|
+
},
|
|
1132
|
+
/**
|
|
1133
|
+
You can use `payloadKeyFromModelName` to override the root key for an outgoing
|
|
1134
|
+
request. By default, the RESTSerializer returns a camelized version of the
|
|
1135
|
+
model's name.
|
|
1136
|
+
For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer
|
|
1137
|
+
will send it to the server with `tacoParty` as the root key in the JSON payload:
|
|
1138
|
+
```js
|
|
1139
|
+
{
|
|
1140
|
+
"tacoParty": {
|
|
1141
|
+
"id": "1",
|
|
1142
|
+
"location": "Matthew Beale's House"
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
```
|
|
1146
|
+
For example, your server may expect dasherized root objects:
|
|
1147
|
+
```js [app/serializers/application.js]
|
|
1148
|
+
import { RESTSerializer } from '@warp-drive/legacy/serializer/rest';
|
|
1149
|
+
import { dasherize } from '<app-name>/utils/string-utils';
|
|
1150
|
+
export default class ApplicationSerializer extends RESTSerializer {
|
|
1151
|
+
payloadKeyFromModelName(modelName) {
|
|
1152
|
+
return dasherize(modelName);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
```
|
|
1156
|
+
Given a `TacoParty` model, calling `save` on it would produce an outgoing
|
|
1157
|
+
request like:
|
|
1158
|
+
```js
|
|
1159
|
+
{
|
|
1160
|
+
"taco-party": {
|
|
1161
|
+
"id": "1",
|
|
1162
|
+
"location": "Matthew Beale's House"
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
```
|
|
1166
|
+
@public
|
|
1167
|
+
*/
|
|
1168
|
+
payloadKeyFromModelName(modelName) {
|
|
1169
|
+
return camelize(modelName);
|
|
1170
|
+
},
|
|
1171
|
+
/**
|
|
1172
|
+
You can use this method to customize how polymorphic objects are serialized.
|
|
1173
|
+
By default the REST Serializer creates the key by appending `Type` to
|
|
1174
|
+
the attribute and value from the model's camelcased model name.
|
|
1175
|
+
@public
|
|
1176
|
+
*/
|
|
1177
|
+
serializePolymorphicType(snapshot, json, relationship) {
|
|
1178
|
+
const name = relationship.name;
|
|
1179
|
+
const typeKey = this.keyForPolymorphicType(name, relationship.type, 'serialize');
|
|
1180
|
+
const belongsTo = snapshot.belongsTo(name);
|
|
1181
|
+
if (!belongsTo) {
|
|
1182
|
+
json[typeKey] = null;
|
|
1183
|
+
} else {
|
|
1184
|
+
// @ts-expect-error
|
|
1185
|
+
json[typeKey] = camelize(belongsTo.modelName);
|
|
1186
|
+
}
|
|
1187
|
+
},
|
|
1188
|
+
/**
|
|
1189
|
+
You can use this method to customize how a polymorphic relationship should
|
|
1190
|
+
be extracted.
|
|
1191
|
+
@public
|
|
1192
|
+
@param {Object} relationshipType
|
|
1193
|
+
@param {Object} relationshipHash
|
|
1194
|
+
@param {Object} relationshipOptions
|
|
1195
|
+
@return {Object}
|
|
1196
|
+
*/
|
|
1197
|
+
extractPolymorphicRelationship(relationshipType, relationshipHash, relationshipOptions) {
|
|
1198
|
+
// @ts-expect-error
|
|
1199
|
+
const {
|
|
1200
|
+
key,
|
|
1201
|
+
resourceHash,
|
|
1202
|
+
relationshipMeta
|
|
1203
|
+
} = relationshipOptions;
|
|
1204
|
+
|
|
1205
|
+
// A polymorphic belongsTo relationship can be present in the payload
|
|
1206
|
+
// either in the form where the `id` and the `type` are given:
|
|
1207
|
+
//
|
|
1208
|
+
// {
|
|
1209
|
+
// message: { id: 1, type: 'post' }
|
|
1210
|
+
// }
|
|
1211
|
+
//
|
|
1212
|
+
// or by the `id` and a `<relationship>Type` attribute:
|
|
1213
|
+
//
|
|
1214
|
+
// {
|
|
1215
|
+
// message: 1,
|
|
1216
|
+
// messageType: 'post'
|
|
1217
|
+
// }
|
|
1218
|
+
//
|
|
1219
|
+
// The next code checks if the latter case is present and returns the
|
|
1220
|
+
// corresponding JSON-API representation. The former case is handled within
|
|
1221
|
+
// the base class JSONSerializer.
|
|
1222
|
+
const isPolymorphic = relationshipMeta.options.polymorphic;
|
|
1223
|
+
const typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize');
|
|
1224
|
+
if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') {
|
|
1225
|
+
const type = this.modelNameFromPayloadKey(resourceHash[typeProperty]);
|
|
1226
|
+
return {
|
|
1227
|
+
id: coerceId(relationshipHash),
|
|
1228
|
+
type: type
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
// @ts-expect-error
|
|
1232
|
+
return this._super(...arguments);
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
{
|
|
1236
|
+
RESTSerializer.reopen({
|
|
1237
|
+
warnMessageNoModelForKey(prop, typeKey) {
|
|
1238
|
+
return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))';
|
|
1239
|
+
}
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
export { EmbeddedRecordsMixin, RESTSerializer };
|