@ember-data-mirror/serializer 5.4.0-alpha.49
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/LICENSE.md +11 -0
- package/README.md +98 -0
- package/addon/-private.js +3 -0
- package/addon/-private.js.map +1 -0
- package/addon/embedded-records-mixin-QJe_8jrF.js +572 -0
- package/addon/embedded-records-mixin-QJe_8jrF.js.map +1 -0
- package/addon/index.js +181 -0
- package/addon/index.js.map +1 -0
- package/addon/json-api.js +508 -0
- package/addon/json-api.js.map +1 -0
- package/addon/json.js +1375 -0
- package/addon/json.js.map +1 -0
- package/addon/rest.js +684 -0
- package/addon/rest.js.map +1 -0
- package/addon/string-Juwz4cu0.js +345 -0
- package/addon/string-Juwz4cu0.js.map +1 -0
- package/addon/transform.js +1 -0
- package/addon/transform.js.map +1 -0
- package/addon/utils-NcVD2Jb5.js +12 -0
- package/addon/utils-NcVD2Jb5.js.map +1 -0
- package/addon-main.js +94 -0
- package/blueprints/serializer/files/__root__/__path__/__name__.js +4 -0
- package/blueprints/serializer/index.js +14 -0
- package/blueprints/serializer/native-files/__root__/__path__/__name__.js +4 -0
- package/blueprints/serializer-test/index.js +29 -0
- package/blueprints/serializer-test/qunit-files/__root__/__path__/__test__.js +24 -0
- package/blueprints/transform/files/__root__/__path__/__name__.js +13 -0
- package/blueprints/transform/index.js +7 -0
- package/blueprints/transform/native-files/__root__/__path__/__name__.js +13 -0
- package/blueprints/transform-test/index.js +29 -0
- package/blueprints/transform-test/qunit-files/__root__/__path__/__test__.js +13 -0
- package/package.json +113 -0
- package/unstable-preview-types/-private/embedded-records-mixin.d.ts +7 -0
- package/unstable-preview-types/-private/embedded-records-mixin.d.ts.map +1 -0
- package/unstable-preview-types/-private/transforms/boolean.d.ts +52 -0
- package/unstable-preview-types/-private/transforms/boolean.d.ts.map +1 -0
- package/unstable-preview-types/-private/transforms/date.d.ts +33 -0
- package/unstable-preview-types/-private/transforms/date.d.ts.map +1 -0
- package/unstable-preview-types/-private/transforms/number.d.ts +34 -0
- package/unstable-preview-types/-private/transforms/number.d.ts.map +1 -0
- package/unstable-preview-types/-private/transforms/string.d.ts +34 -0
- package/unstable-preview-types/-private/transforms/string.d.ts.map +1 -0
- package/unstable-preview-types/-private/transforms/transform.d.ts +128 -0
- package/unstable-preview-types/-private/transforms/transform.d.ts.map +1 -0
- package/unstable-preview-types/-private/utils.d.ts +6 -0
- package/unstable-preview-types/-private/utils.d.ts.map +1 -0
- package/unstable-preview-types/-private.d.ts +13 -0
- package/unstable-preview-types/-private.d.ts.map +1 -0
- package/unstable-preview-types/index.d.ts +278 -0
- package/unstable-preview-types/index.d.ts.map +1 -0
- package/unstable-preview-types/json-api.d.ts +515 -0
- package/unstable-preview-types/json-api.d.ts.map +1 -0
- package/unstable-preview-types/json.d.ts +1094 -0
- package/unstable-preview-types/json.d.ts.map +1 -0
- package/unstable-preview-types/rest.d.ts +602 -0
- package/unstable-preview-types/rest.d.ts.map +1 -0
- package/unstable-preview-types/transform.d.ts +7 -0
- package/unstable-preview-types/transform.d.ts.map +1 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (C) 2017-2023 Ember.js contributors
|
|
4
|
+
Portions Copyright (C) 2011-2017 Tilde, Inc. and contributors.
|
|
5
|
+
Portions Copyright (C) 2011 LivingSocial Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
8
|
+
|
|
9
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img
|
|
3
|
+
class="project-logo"
|
|
4
|
+
src="./ember-data-logo-dark.svg#gh-dark-mode-only"
|
|
5
|
+
alt="EmberData Serializer"
|
|
6
|
+
width="240px"
|
|
7
|
+
title="EmberData Serializer"
|
|
8
|
+
/>
|
|
9
|
+
<img
|
|
10
|
+
class="project-logo"
|
|
11
|
+
src="./ember-data-logo-light.svg#gh-light-mode-only"
|
|
12
|
+
alt="EmberData Serializer"
|
|
13
|
+
width="240px"
|
|
14
|
+
title="EmberData Serializer"
|
|
15
|
+
/>
|
|
16
|
+
</p>
|
|
17
|
+
|
|
18
|
+
<p align="center">Provides JSON, REST and JSON:API Implementations of the legacy <a href="https://api.emberjs.com/ember-data/release/classes/%3CInterface%3E%20Serializer">Serializer Interface</a></p>
|
|
19
|
+
|
|
20
|
+
> **Caution** ⚠️ **This is LEGACY documentation** for a feature that is no longer encouraged to be used.
|
|
21
|
+
> If starting a new app or thinking of implementing a new serializer, consider writing a [Handler](https://api.emberjs.com/ember-data/release/classes/%3CInterface%3E%20Handler)
|
|
22
|
+
> instead to be used with the [RequestManager](https://github.com/emberjs/data/tree/main/packages/request#readme)
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
This package is currently installed when installing `ember-data`.
|
|
27
|
+
|
|
28
|
+
If installing `@ember-data/` packages individually install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
|
|
29
|
+
|
|
30
|
+
```no-highlight
|
|
31
|
+
pnpm add @ember-data-mirror/serializer
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## 🚀 Setup
|
|
35
|
+
|
|
36
|
+
If using `ember-data` no additional setup is necesssary.
|
|
37
|
+
|
|
38
|
+
> **Note**
|
|
39
|
+
> When using [ember-data](https://github.com/emberjs/data/blob/main/packages/-ember-data) the below
|
|
40
|
+
> configuration is handled for you automatically.
|
|
41
|
+
|
|
42
|
+
To use legacy serializers you will need to have installed and configured the LegacyNetworkHandler from [@ember-data-mirror/legacy-compat](https://github.com/emberjs/data/blob/main/packages/-ember-data)
|
|
43
|
+
|
|
44
|
+
```no-highlight
|
|
45
|
+
pnpm add @ember-data-mirror/legacy-compat
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import Store, { CacheHandler } from '@ember-data-mirror/store';
|
|
50
|
+
import RequestManager from '@ember-data-mirror/request';
|
|
51
|
+
import { LegacyNetworkHandler } from '@ember-data-mirror/legacy-compat';
|
|
52
|
+
|
|
53
|
+
export default class extends Store {
|
|
54
|
+
requestManager = new RequestManager();
|
|
55
|
+
|
|
56
|
+
constructor(args) {
|
|
57
|
+
super(args);
|
|
58
|
+
this.requestManager.use([LegacyNetworkHandler]);
|
|
59
|
+
this.requestManager.useCache(CacheHandler);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
To use as either a per-type or application serializer, export one of the
|
|
68
|
+
implementations within the `serializers/` directory of your app as appropriate.
|
|
69
|
+
|
|
70
|
+
For instance, to configure an application serializer to use `JSON:API`
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
*app/serializers/application.ts*
|
|
74
|
+
```ts
|
|
75
|
+
export { default } from '@ember-data-mirror/serializer/json-api';
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
By default serializers are resolved by looking for a serializer with the same name in the `serializers/` folder as the `type` given to `store.serializerFor(<type>)`, falling back to looking for a serializer named `application`.
|
|
79
|
+
|
|
80
|
+
**Overriding Resolution**
|
|
81
|
+
|
|
82
|
+
If you would like to avoid using resolver semantics and your application has only one or a few serializers, you may ovveride the `serializerFor` hook on the store.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import Store from '@ember-data-mirror/store';
|
|
86
|
+
import Serializer from '@ember-data-mirror/serializer/json-api';
|
|
87
|
+
|
|
88
|
+
class extends Store {
|
|
89
|
+
#serializer = new Serializer();
|
|
90
|
+
|
|
91
|
+
serializerFor() {
|
|
92
|
+
return this.#serializer;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
For the full list of APIs available read the code documentation for [@ember-data-mirror/serializer](https://api.emberjs.com/ember-data/release/modules/@ember-data%2Fserializer). You may also be interested in learning more about *Ember***Data**'s [Serializer Interface](https://api.emberjs.com/ember-data/release/classes/%3CInterface%3E%20Serializer).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"-private.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
|
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
import { warn } from '@ember/debug';
|
|
2
|
+
import Mixin from '@ember/object/mixin';
|
|
3
|
+
import { camelize } from '@ember/string';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
@module @ember-data-mirror/serializer/rest
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
## Using Embedded Records
|
|
11
|
+
|
|
12
|
+
`EmbeddedRecordsMixin` supports serializing embedded records.
|
|
13
|
+
|
|
14
|
+
To set up embedded records, include the mixin when extending a serializer,
|
|
15
|
+
then define and configure embedded (model) relationships.
|
|
16
|
+
|
|
17
|
+
Note that embedded records will serialize with the serializer for their model instead of the serializer in which they are defined.
|
|
18
|
+
|
|
19
|
+
Note also that this mixin does not work with JSONAPISerializer because the JSON:API specification does not describe how to format embedded resources.
|
|
20
|
+
|
|
21
|
+
Below is an example of a per-type serializer (`post` type).
|
|
22
|
+
|
|
23
|
+
```app/serializers/post.js
|
|
24
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
|
|
25
|
+
|
|
26
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
27
|
+
attrs = {
|
|
28
|
+
author: { embedded: 'always' },
|
|
29
|
+
comments: { serialize: 'ids' }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
Note that this use of `{ embedded: 'always' }` is unrelated to
|
|
34
|
+
the `{ embedded: 'always' }` that is defined as an option on `attr` as part of
|
|
35
|
+
defining a model while working with the `ActiveModelSerializer`. Nevertheless,
|
|
36
|
+
using `{ embedded: 'always' }` as an option to `attr` is not a valid way to set up
|
|
37
|
+
embedded records.
|
|
38
|
+
|
|
39
|
+
The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
{
|
|
43
|
+
serialize: 'records',
|
|
44
|
+
deserialize: 'records'
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Configuring Attrs
|
|
49
|
+
|
|
50
|
+
A resource's `attrs` option may be set to use `ids`, `records` or false for the
|
|
51
|
+
`serialize` and `deserialize` settings.
|
|
52
|
+
|
|
53
|
+
The `attrs` property can be set on the `ApplicationSerializer` or a per-type
|
|
54
|
+
serializer.
|
|
55
|
+
|
|
56
|
+
In the case where embedded JSON is expected while extracting a payload (reading)
|
|
57
|
+
the setting is `deserialize: 'records'`, there is no need to use `ids` when
|
|
58
|
+
extracting as that is the default behaviour without this mixin if you are using
|
|
59
|
+
the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while
|
|
60
|
+
serializing `serialize: 'records'` is the setting to use. There is an option of
|
|
61
|
+
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
|
|
62
|
+
do not want the relationship sent at all, you can use `serialize: false`.
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
### EmbeddedRecordsMixin defaults
|
|
66
|
+
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
|
|
67
|
+
will behave in the following way:
|
|
68
|
+
|
|
69
|
+
BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
|
|
70
|
+
HasMany: `{ serialize: false, deserialize: 'ids' }`
|
|
71
|
+
|
|
72
|
+
### Model Relationships
|
|
73
|
+
|
|
74
|
+
Embedded records must have a model defined to be extracted and serialized. Note that
|
|
75
|
+
when defining any relationships on your model such as `belongsTo` and `hasMany`, you
|
|
76
|
+
should not both specify `async: true` and also indicate through the serializer's
|
|
77
|
+
`attrs` attribute that the related model should be embedded for deserialization.
|
|
78
|
+
If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`),
|
|
79
|
+
then do not use `async: true`.
|
|
80
|
+
|
|
81
|
+
To successfully extract and serialize embedded records the model relationships
|
|
82
|
+
must be set up correctly. See the
|
|
83
|
+
[defining relationships](https://guides.emberjs.com/current/models/relationships)
|
|
84
|
+
section of the **Defining Models** guide page.
|
|
85
|
+
|
|
86
|
+
Records without an `id` property are not considered embedded records, model
|
|
87
|
+
instances must have an `id` property to be used with Ember Data.
|
|
88
|
+
|
|
89
|
+
### Example JSON payloads, Models and Serializers
|
|
90
|
+
|
|
91
|
+
**When customizing a serializer it is important to grok what the customizations
|
|
92
|
+
are. Please read the docs for the methods this mixin provides, in case you need
|
|
93
|
+
to modify it to fit your specific needs.**
|
|
94
|
+
|
|
95
|
+
For example, review the docs for each method of this mixin:
|
|
96
|
+
* [normalize](/ember-data/release/classes/EmbeddedRecordsMixin/methods/normalize?anchor=normalize)
|
|
97
|
+
* [serializeBelongsTo](/ember-data/release/classes/EmbeddedRecordsMixin/methods/serializeBelongsTo?anchor=serializeBelongsTo)
|
|
98
|
+
* [serializeHasMany](/ember-data/release/classes/EmbeddedRecordsMixin/methods/serializeHasMany?anchor=serializeHasMany)
|
|
99
|
+
|
|
100
|
+
@class EmbeddedRecordsMixin
|
|
101
|
+
@public
|
|
102
|
+
*/
|
|
103
|
+
var embeddedRecordsMixin = Mixin.create({
|
|
104
|
+
/**
|
|
105
|
+
Normalize the record and recursively normalize/extract all the embedded records
|
|
106
|
+
while pushing them into the store as they are encountered
|
|
107
|
+
A payload with an attr configured for embedded records needs to be extracted:
|
|
108
|
+
```js
|
|
109
|
+
{
|
|
110
|
+
"post": {
|
|
111
|
+
"id": "1"
|
|
112
|
+
"title": "Rails is omakase",
|
|
113
|
+
"comments": [{
|
|
114
|
+
"id": "1",
|
|
115
|
+
"body": "Rails is unagi"
|
|
116
|
+
}, {
|
|
117
|
+
"id": "2",
|
|
118
|
+
"body": "Omakase O_o"
|
|
119
|
+
}]
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
@method normalize
|
|
124
|
+
@public
|
|
125
|
+
@param {Model} typeClass
|
|
126
|
+
@param {Object} hash to be normalized
|
|
127
|
+
@param {String} prop the hash has been referenced by
|
|
128
|
+
@return {Object} the normalized hash
|
|
129
|
+
**/
|
|
130
|
+
normalize(typeClass, hash, prop) {
|
|
131
|
+
const normalizedHash = this._super(typeClass, hash, prop);
|
|
132
|
+
return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash);
|
|
133
|
+
},
|
|
134
|
+
keyForRelationship(key, typeClass, method) {
|
|
135
|
+
if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) {
|
|
136
|
+
return this.keyForAttribute(key, method);
|
|
137
|
+
} else {
|
|
138
|
+
return this._super(key, typeClass, method) || key;
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
/**
|
|
142
|
+
Serialize `belongsTo` relationship when it is configured as an embedded object.
|
|
143
|
+
This example of an author model belongs to a post model:
|
|
144
|
+
```js
|
|
145
|
+
import Model, { attr, belongsTo } from '@ember-data-mirror/model';
|
|
146
|
+
Post = Model.extend({
|
|
147
|
+
title: attr('string'),
|
|
148
|
+
body: attr('string'),
|
|
149
|
+
author: belongsTo('author')
|
|
150
|
+
});
|
|
151
|
+
Author = Model.extend({
|
|
152
|
+
name: attr('string'),
|
|
153
|
+
post: belongsTo('post')
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
Use a custom (type) serializer for the post model to configure embedded author
|
|
157
|
+
```app/serializers/post.js
|
|
158
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
|
|
159
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
160
|
+
attrs = {
|
|
161
|
+
author: { embedded: 'always' }
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
A payload with an attribute configured for embedded records can serialize
|
|
166
|
+
the records together under the root attribute's payload:
|
|
167
|
+
```js
|
|
168
|
+
{
|
|
169
|
+
"post": {
|
|
170
|
+
"id": "1"
|
|
171
|
+
"title": "Rails is omakase",
|
|
172
|
+
"author": {
|
|
173
|
+
"id": "2"
|
|
174
|
+
"name": "dhh"
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
@method serializeBelongsTo
|
|
180
|
+
@public
|
|
181
|
+
@param {Snapshot} snapshot
|
|
182
|
+
@param {Object} json
|
|
183
|
+
@param {Object} relationship
|
|
184
|
+
*/
|
|
185
|
+
serializeBelongsTo(snapshot, json, relationship) {
|
|
186
|
+
const attr = relationship.name;
|
|
187
|
+
if (this.noSerializeOptionSpecified(attr)) {
|
|
188
|
+
this._super(snapshot, json, relationship);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const includeIds = this.hasSerializeIdsOption(attr);
|
|
192
|
+
const includeRecords = this.hasSerializeRecordsOption(attr);
|
|
193
|
+
const embeddedSnapshot = snapshot.belongsTo(attr);
|
|
194
|
+
if (includeIds) {
|
|
195
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
196
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
197
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
198
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
199
|
+
}
|
|
200
|
+
if (!embeddedSnapshot) {
|
|
201
|
+
json[serializedKey] = null;
|
|
202
|
+
} else {
|
|
203
|
+
json[serializedKey] = embeddedSnapshot.id;
|
|
204
|
+
if (relationship.options.polymorphic) {
|
|
205
|
+
this.serializePolymorphicType(snapshot, json, relationship);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
} else if (includeRecords) {
|
|
209
|
+
this._serializeEmbeddedBelongsTo(snapshot, json, relationship);
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
_serializeEmbeddedBelongsTo(snapshot, json, relationship) {
|
|
213
|
+
const embeddedSnapshot = snapshot.belongsTo(relationship.name);
|
|
214
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
215
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
216
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
217
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
218
|
+
}
|
|
219
|
+
if (!embeddedSnapshot) {
|
|
220
|
+
json[serializedKey] = null;
|
|
221
|
+
} else {
|
|
222
|
+
json[serializedKey] = embeddedSnapshot.serialize({
|
|
223
|
+
includeId: true
|
|
224
|
+
});
|
|
225
|
+
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]);
|
|
226
|
+
if (relationship.options.polymorphic) {
|
|
227
|
+
this.serializePolymorphicType(snapshot, json, relationship);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
},
|
|
231
|
+
/**
|
|
232
|
+
Serializes `hasMany` relationships when it is configured as embedded objects.
|
|
233
|
+
This example of a post model has many comments:
|
|
234
|
+
```js
|
|
235
|
+
import Model, { attr, belongsTo, hasMany } from '@ember-data-mirror/model';
|
|
236
|
+
Post = Model.extend({
|
|
237
|
+
title: attr('string'),
|
|
238
|
+
body: attr('string'),
|
|
239
|
+
comments: hasMany('comment')
|
|
240
|
+
});
|
|
241
|
+
Comment = Model.extend({
|
|
242
|
+
body: attr('string'),
|
|
243
|
+
post: belongsTo('post')
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
Use a custom (type) serializer for the post model to configure embedded comments
|
|
247
|
+
```app/serializers/post.js
|
|
248
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
|
|
249
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
250
|
+
attrs = {
|
|
251
|
+
comments: { embedded: 'always' }
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
```
|
|
255
|
+
A payload with an attribute configured for embedded records can serialize
|
|
256
|
+
the records together under the root attribute's payload:
|
|
257
|
+
```js
|
|
258
|
+
{
|
|
259
|
+
"post": {
|
|
260
|
+
"id": "1"
|
|
261
|
+
"title": "Rails is omakase",
|
|
262
|
+
"body": "I want this for my ORM, I want that for my template language..."
|
|
263
|
+
"comments": [{
|
|
264
|
+
"id": "1",
|
|
265
|
+
"body": "Rails is unagi"
|
|
266
|
+
}, {
|
|
267
|
+
"id": "2",
|
|
268
|
+
"body": "Omakase O_o"
|
|
269
|
+
}]
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
The attrs options object can use more specific instruction for extracting and
|
|
274
|
+
serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set.
|
|
275
|
+
When extracting the only option is `records`.
|
|
276
|
+
So `{ embedded: 'always' }` is shorthand for:
|
|
277
|
+
`{ serialize: 'records', deserialize: 'records' }`
|
|
278
|
+
To embed the `ids` for a related object (using a hasMany relationship):
|
|
279
|
+
```app/serializers/post.js
|
|
280
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
|
|
281
|
+
export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
282
|
+
attrs = {
|
|
283
|
+
comments: { serialize: 'ids', deserialize: 'records' }
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
```js
|
|
288
|
+
{
|
|
289
|
+
"post": {
|
|
290
|
+
"id": "1"
|
|
291
|
+
"title": "Rails is omakase",
|
|
292
|
+
"body": "I want this for my ORM, I want that for my template language..."
|
|
293
|
+
"comments": ["1", "2"]
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
To embed the relationship as a collection of objects with `id` and `type` keys, set
|
|
298
|
+
`ids-and-types` for the related object.
|
|
299
|
+
This is particularly useful for polymorphic relationships where records don't share
|
|
300
|
+
the same table and the `id` is not enough information.
|
|
301
|
+
For example having a user that has many pets:
|
|
302
|
+
```js
|
|
303
|
+
User = Model.extend({
|
|
304
|
+
name: attr('string'),
|
|
305
|
+
pets: hasMany('pet', { polymorphic: true })
|
|
306
|
+
});
|
|
307
|
+
Pet = Model.extend({
|
|
308
|
+
name: attr('string'),
|
|
309
|
+
});
|
|
310
|
+
Cat = Pet.extend({
|
|
311
|
+
// ...
|
|
312
|
+
});
|
|
313
|
+
Parrot = Pet.extend({
|
|
314
|
+
// ...
|
|
315
|
+
});
|
|
316
|
+
```
|
|
317
|
+
```app/serializers/user.js
|
|
318
|
+
import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
|
|
319
|
+
export default class UserSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
|
|
320
|
+
attrs = {
|
|
321
|
+
pets: { serialize: 'ids-and-types', deserialize: 'records' }
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
```js
|
|
326
|
+
{
|
|
327
|
+
"user": {
|
|
328
|
+
"id": "1"
|
|
329
|
+
"name": "Bertin Osborne",
|
|
330
|
+
"pets": [
|
|
331
|
+
{ "id": "1", "type": "Cat" },
|
|
332
|
+
{ "id": "1", "type": "Parrot"}
|
|
333
|
+
]
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
```
|
|
337
|
+
@method serializeHasMany
|
|
338
|
+
@public
|
|
339
|
+
@param {Snapshot} snapshot
|
|
340
|
+
@param {Object} json
|
|
341
|
+
@param {Object} relationship
|
|
342
|
+
*/
|
|
343
|
+
serializeHasMany(snapshot, json, relationship) {
|
|
344
|
+
const attr = relationship.name;
|
|
345
|
+
if (this.noSerializeOptionSpecified(attr)) {
|
|
346
|
+
this._super(snapshot, json, relationship);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (this.hasSerializeIdsOption(attr)) {
|
|
350
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
351
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
352
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
353
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
354
|
+
}
|
|
355
|
+
json[serializedKey] = snapshot.hasMany(attr, {
|
|
356
|
+
ids: true
|
|
357
|
+
});
|
|
358
|
+
} else if (this.hasSerializeRecordsOption(attr)) {
|
|
359
|
+
this._serializeEmbeddedHasMany(snapshot, json, relationship);
|
|
360
|
+
} else {
|
|
361
|
+
if (this.hasSerializeIdsAndTypesOption(attr)) {
|
|
362
|
+
this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
},
|
|
366
|
+
/*
|
|
367
|
+
Serializes a hasMany relationship as an array of objects containing only `id` and `type`
|
|
368
|
+
keys.
|
|
369
|
+
This has its use case on polymorphic hasMany relationships where the server is not storing
|
|
370
|
+
all records in the same table using STI, and therefore the `id` is not enough information
|
|
371
|
+
TODO: Make the default in Ember-data 3.0??
|
|
372
|
+
*/
|
|
373
|
+
_serializeHasManyAsIdsAndTypes(snapshot, json, relationship) {
|
|
374
|
+
const serializedKey = this.keyForAttribute(relationship.name, 'serialize');
|
|
375
|
+
const hasMany = snapshot.hasMany(relationship.name) || [];
|
|
376
|
+
json[serializedKey] = hasMany.map(function (recordSnapshot) {
|
|
377
|
+
//
|
|
378
|
+
// I'm sure I'm being utterly naive here. Probably id is a configurable property and
|
|
379
|
+
// type too, and the modelName has to be normalized somehow.
|
|
380
|
+
//
|
|
381
|
+
return {
|
|
382
|
+
id: recordSnapshot.id,
|
|
383
|
+
type: recordSnapshot.modelName
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
},
|
|
387
|
+
_serializeEmbeddedHasMany(snapshot, json, relationship) {
|
|
388
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
389
|
+
let serializedKey = this._getMappedKey(relationship.name, schema);
|
|
390
|
+
if (serializedKey === relationship.name && this.keyForRelationship) {
|
|
391
|
+
serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
|
|
392
|
+
}
|
|
393
|
+
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', {
|
|
394
|
+
id: 'ds.serializer.embedded-relationship-undefined'
|
|
395
|
+
});
|
|
396
|
+
json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship);
|
|
397
|
+
},
|
|
398
|
+
/*
|
|
399
|
+
Returns an array of embedded records serialized to JSON
|
|
400
|
+
*/
|
|
401
|
+
_generateSerializedHasMany(snapshot, relationship) {
|
|
402
|
+
const hasMany = snapshot.hasMany(relationship.name) || [];
|
|
403
|
+
const ret = new Array(hasMany.length);
|
|
404
|
+
for (let i = 0; i < hasMany.length; i++) {
|
|
405
|
+
const embeddedSnapshot = hasMany[i];
|
|
406
|
+
const embeddedJson = embeddedSnapshot.serialize({
|
|
407
|
+
includeId: true
|
|
408
|
+
});
|
|
409
|
+
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
|
|
410
|
+
ret[i] = embeddedJson;
|
|
411
|
+
}
|
|
412
|
+
return ret;
|
|
413
|
+
},
|
|
414
|
+
/**
|
|
415
|
+
When serializing an embedded record, modify the property (in the `JSON` payload)
|
|
416
|
+
that refers to the parent record (foreign key for the relationship).
|
|
417
|
+
Serializing a `belongsTo` relationship removes the property that refers to the
|
|
418
|
+
parent record
|
|
419
|
+
Serializing a `hasMany` relationship does not remove the property that refers to
|
|
420
|
+
the parent record.
|
|
421
|
+
@method removeEmbeddedForeignKey
|
|
422
|
+
@public
|
|
423
|
+
@param {Snapshot} snapshot
|
|
424
|
+
@param {Snapshot} embeddedSnapshot
|
|
425
|
+
@param {Object} relationship
|
|
426
|
+
@param {Object} json
|
|
427
|
+
*/
|
|
428
|
+
removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json) {
|
|
429
|
+
if (relationship.kind === 'belongsTo') {
|
|
430
|
+
const schema = this.store.modelFor(snapshot.modelName);
|
|
431
|
+
const parentRecord = schema.inverseFor(relationship.name, this.store);
|
|
432
|
+
if (parentRecord) {
|
|
433
|
+
const name = parentRecord.name;
|
|
434
|
+
const embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName);
|
|
435
|
+
const parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize');
|
|
436
|
+
if (parentKey) {
|
|
437
|
+
delete json[parentKey];
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
} /*else if (relationship.kind === 'hasMany') {
|
|
441
|
+
return;
|
|
442
|
+
}*/
|
|
443
|
+
},
|
|
444
|
+
// checks config for attrs option to embedded (always) - serialize and deserialize
|
|
445
|
+
hasEmbeddedAlwaysOption(attr) {
|
|
446
|
+
const option = this.attrsOption(attr);
|
|
447
|
+
return option && option.embedded === 'always';
|
|
448
|
+
},
|
|
449
|
+
// checks config for attrs option to serialize ids
|
|
450
|
+
hasSerializeRecordsOption(attr) {
|
|
451
|
+
const alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
|
|
452
|
+
const option = this.attrsOption(attr);
|
|
453
|
+
return alwaysEmbed || option && option.serialize === 'records';
|
|
454
|
+
},
|
|
455
|
+
// checks config for attrs option to serialize records
|
|
456
|
+
hasSerializeIdsOption(attr) {
|
|
457
|
+
const option = this.attrsOption(attr);
|
|
458
|
+
return option && (option.serialize === 'ids' || option.serialize === 'id');
|
|
459
|
+
},
|
|
460
|
+
// checks config for attrs option to serialize records as objects containing id and types
|
|
461
|
+
hasSerializeIdsAndTypesOption(attr) {
|
|
462
|
+
const option = this.attrsOption(attr);
|
|
463
|
+
return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type');
|
|
464
|
+
},
|
|
465
|
+
// checks config for attrs option to serialize records
|
|
466
|
+
noSerializeOptionSpecified(attr) {
|
|
467
|
+
const option = this.attrsOption(attr);
|
|
468
|
+
return !(option && (option.serialize || option.embedded));
|
|
469
|
+
},
|
|
470
|
+
// checks config for attrs option to deserialize records
|
|
471
|
+
// a defined option object for a resource is treated the same as
|
|
472
|
+
// `deserialize: 'records'`
|
|
473
|
+
hasDeserializeRecordsOption(attr) {
|
|
474
|
+
const alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
|
|
475
|
+
const option = this.attrsOption(attr);
|
|
476
|
+
return alwaysEmbed || option && option.deserialize === 'records';
|
|
477
|
+
},
|
|
478
|
+
attrsOption(attr) {
|
|
479
|
+
const attrs = this.attrs;
|
|
480
|
+
return attrs && (attrs[camelize(attr)] || attrs[attr]);
|
|
481
|
+
},
|
|
482
|
+
/**
|
|
483
|
+
@method _extractEmbeddedRecords
|
|
484
|
+
@private
|
|
485
|
+
*/
|
|
486
|
+
_extractEmbeddedRecords(serializer, store, typeClass, partial) {
|
|
487
|
+
typeClass.eachRelationship((key, relationship) => {
|
|
488
|
+
if (serializer.hasDeserializeRecordsOption(key)) {
|
|
489
|
+
if (relationship.kind === 'hasMany') {
|
|
490
|
+
this._extractEmbeddedHasMany(store, key, partial, relationship);
|
|
491
|
+
}
|
|
492
|
+
if (relationship.kind === 'belongsTo') {
|
|
493
|
+
this._extractEmbeddedBelongsTo(store, key, partial, relationship);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
return partial;
|
|
498
|
+
},
|
|
499
|
+
/**
|
|
500
|
+
@method _extractEmbeddedHasMany
|
|
501
|
+
@private
|
|
502
|
+
*/
|
|
503
|
+
_extractEmbeddedHasMany(store, key, hash, relationshipMeta) {
|
|
504
|
+
const relationshipHash = hash.data?.relationships?.[key]?.data;
|
|
505
|
+
if (!relationshipHash) {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const hasMany = new Array(relationshipHash.length);
|
|
509
|
+
for (let i = 0; i < relationshipHash.length; i++) {
|
|
510
|
+
const item = relationshipHash[i];
|
|
511
|
+
const {
|
|
512
|
+
data,
|
|
513
|
+
included
|
|
514
|
+
} = this._normalizeEmbeddedRelationship(store, relationshipMeta, item);
|
|
515
|
+
hash.included = hash.included || [];
|
|
516
|
+
hash.included.push(data);
|
|
517
|
+
if (included) {
|
|
518
|
+
hash.included = hash.included.concat(included);
|
|
519
|
+
}
|
|
520
|
+
hasMany[i] = {
|
|
521
|
+
id: data.id,
|
|
522
|
+
type: data.type
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
const relationship = {
|
|
526
|
+
data: hasMany
|
|
527
|
+
};
|
|
528
|
+
hash.data.relationships[key] = relationship;
|
|
529
|
+
},
|
|
530
|
+
/**
|
|
531
|
+
@method _extractEmbeddedBelongsTo
|
|
532
|
+
@private
|
|
533
|
+
*/
|
|
534
|
+
_extractEmbeddedBelongsTo(store, key, hash, relationshipMeta) {
|
|
535
|
+
const relationshipHash = hash.data?.relationships?.[key]?.data;
|
|
536
|
+
if (!relationshipHash) {
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const {
|
|
540
|
+
data,
|
|
541
|
+
included
|
|
542
|
+
} = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash);
|
|
543
|
+
hash.included = hash.included || [];
|
|
544
|
+
hash.included.push(data);
|
|
545
|
+
if (included) {
|
|
546
|
+
hash.included = hash.included.concat(included);
|
|
547
|
+
}
|
|
548
|
+
const belongsTo = {
|
|
549
|
+
id: data.id,
|
|
550
|
+
type: data.type
|
|
551
|
+
};
|
|
552
|
+
const relationship = {
|
|
553
|
+
data: belongsTo
|
|
554
|
+
};
|
|
555
|
+
hash.data.relationships[key] = relationship;
|
|
556
|
+
},
|
|
557
|
+
/**
|
|
558
|
+
@method _normalizeEmbeddedRelationship
|
|
559
|
+
@private
|
|
560
|
+
*/
|
|
561
|
+
_normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash) {
|
|
562
|
+
let modelName = relationshipMeta.type;
|
|
563
|
+
if (relationshipMeta.options.polymorphic) {
|
|
564
|
+
modelName = relationshipHash.type;
|
|
565
|
+
}
|
|
566
|
+
const modelClass = store.modelFor(modelName);
|
|
567
|
+
const serializer = store.serializerFor(modelName);
|
|
568
|
+
return serializer.normalize(modelClass, relationshipHash, null);
|
|
569
|
+
},
|
|
570
|
+
isEmbeddedRecordsMixin: true
|
|
571
|
+
});
|
|
572
|
+
export { embeddedRecordsMixin as e };
|