-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathschema.ts
335 lines (302 loc) · 11.8 KB
/
schema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { deprecate } from '@ember/debug';
import { recordIdentifierFor } from '@ember-data/store';
import type { SchemaService as SchemaServiceInterface } from '@ember-data/store/types';
import { createCache, getValue } from '@ember-data/tracking';
import type { Signal } from '@ember-data/tracking/-private';
import { Signals } from '@ember-data/tracking/-private';
import { ENABLE_LEGACY_SCHEMA_SERVICE } from '@warp-drive/build-config/deprecations';
import { assert } from '@warp-drive/build-config/macros';
import type { StableRecordIdentifier } from '@warp-drive/core-types';
import { getOrSetGlobal } from '@warp-drive/core-types/-private';
import type { ObjectValue, Value } from '@warp-drive/core-types/json/raw';
import type { Derivation, HashFn } from '@warp-drive/core-types/schema/concepts';
import type {
ArrayField,
DerivedField,
FieldSchema,
GenericField,
HashField,
LegacyAttributeField,
LegacyRelationshipSchema,
ObjectField,
ResourceSchema,
} from '@warp-drive/core-types/schema/fields';
import { Type } from '@warp-drive/core-types/symbols';
import type { WithPartial } from '@warp-drive/core-types/utils';
import type { SchemaRecord } from './record';
import { Identifier } from './symbols';
const Support = getOrSetGlobal('Support', new WeakMap<WeakKey, Record<string, unknown>>());
export const SchemaRecordFields: FieldSchema[] = [
{
type: '@constructor',
name: 'constructor',
kind: 'derived',
},
{
type: '@identity',
name: '$type',
kind: 'derived',
options: { key: 'type' },
},
];
function _constructor(record: SchemaRecord) {
let state = Support.get(record as WeakKey);
if (!state) {
state = {};
Support.set(record as WeakKey, state);
}
return (state._constructor = state._constructor || {
name: `SchemaRecord<${recordIdentifierFor(record).type}>`,
get modelName() {
throw new Error('Cannot access record.constructor.modelName on non-Legacy Schema Records.');
},
});
}
_constructor[Type] = '@constructor';
export function withDefaults(schema: WithPartial<ResourceSchema, 'identity'>): ResourceSchema {
schema.identity = schema.identity || { name: 'id', kind: '@id' };
schema.fields.push(...SchemaRecordFields);
return schema as ResourceSchema;
}
export function fromIdentity(record: SchemaRecord, options: { key: 'lid' } | { key: 'type' }, key: string): string;
export function fromIdentity(record: SchemaRecord, options: { key: 'id' }, key: string): string | null;
export function fromIdentity(record: SchemaRecord, options: { key: '^' }, key: string): StableRecordIdentifier;
export function fromIdentity(record: SchemaRecord, options: null, key: string): asserts options;
export function fromIdentity(
record: SchemaRecord,
options: { key: 'id' | 'lid' | 'type' | '^' } | null,
key: string
): StableRecordIdentifier | string | null {
const identifier = record[Identifier];
assert(`Cannot compute @identity for a record without an identifier`, identifier);
assert(
`Expected to receive a key to compute @identity, but got ${String(options)}`,
options?.key && ['lid', 'id', 'type', '^'].includes(options.key)
);
return options.key === '^' ? identifier : identifier[options.key];
}
fromIdentity[Type] = '@identity';
export function registerDerivations(schema: SchemaServiceInterface) {
schema.registerDerivation(fromIdentity);
schema.registerDerivation(_constructor);
}
type InternalSchema = {
original: ResourceSchema;
traits: Set<string>;
fields: Map<string, FieldSchema>;
attributes: Record<string, LegacyAttributeField>;
relationships: Record<string, LegacyRelationshipSchema>;
};
export type Transformation<T extends Value = Value, PT = unknown> = {
serialize(value: PT, options: Record<string, unknown> | null, record: SchemaRecord): T;
hydrate(value: T | undefined, options: Record<string, unknown> | null, record: SchemaRecord): PT;
defaultValue?(options: Record<string, unknown> | null, identifier: StableRecordIdentifier): T;
[Type]: string;
};
/**
* Wraps a derivation in a new function with Derivation signature but that looks
* up the value in the cache before recomputing.
*
* @param record
* @param options
* @param prop
*/
function makeCachedDerivation<R, T, FM extends ObjectValue | null>(
derivation: Derivation<R, T, FM>
): Derivation<R, T, FM> {
const memoizedDerivation = (record: R, options: FM, prop: string): T => {
const signals = (record as { [Signals]: Map<string, Signal> })[Signals];
let signal = signals.get(prop);
if (!signal) {
signal = createCache(() => {
return derivation(record, options, prop);
}) as unknown as Signal; // a total lie, for convenience of reusing the storage
signals.set(prop, signal);
}
return getValue(signal as unknown as ReturnType<typeof createCache>) as T;
};
memoizedDerivation[Type] = derivation[Type];
return memoizedDerivation;
}
export interface SchemaService {
doesTypeExist(type: string): boolean;
attributesDefinitionFor(identifier: { type: string }): InternalSchema['attributes'];
relationshipsDefinitionFor(identifier: { type: string }): InternalSchema['relationships'];
}
export class SchemaService implements SchemaServiceInterface {
declare _schemas: Map<string, InternalSchema>;
declare _transforms: Map<string, Transformation>;
declare _hashFns: Map<string, HashFn>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare _derivations: Map<string, Derivation<any, any, any>>;
declare _traits: Set<string>;
constructor() {
this._schemas = new Map();
this._transforms = new Map();
this._hashFns = new Map();
this._derivations = new Map();
}
hasTrait(type: string): boolean {
return this._traits.has(type);
}
resourceHasTrait(resource: StableRecordIdentifier | { type: string }, trait: string): boolean {
return this._schemas.get(resource.type)!.traits.has(trait);
}
transformation(field: GenericField | ObjectField | ArrayField | { type: string }): Transformation {
const kind = 'kind' in field ? field.kind : '<unknown kind>';
const name = 'name' in field ? field.name : '<unknown name>';
assert(
`'${kind}' fields cannot be transformed. Only fields of kind 'field' 'object' or 'array' can specify a transformation. Attempted to find '${field.type ?? '<unknown type>'}' on field '${name}'.`,
!('kind' in field) || ['field', 'object', 'array'].includes(kind)
);
assert(
`Expected the '${kind}' field '${name}' to specify a transformation via 'field.type', but none was present`,
field.type
);
assert(
`No transformation registered with name '${field.type}' for '${kind}' field '${name}'`,
this._transforms.has(field.type)
);
return this._transforms.get(field.type)!;
}
derivation(field: DerivedField | { type: string }): Derivation {
const kind = 'kind' in field ? field.kind : '<unknown kind>';
const name = 'name' in field ? field.name : '<unknown name>';
assert(
`The '${kind}' field '${name}' is not derived and so cannot be used to lookup a derivation`,
!('kind' in field) || kind === 'derived'
);
assert(
`Expected the '${kind}' field '${name}' to specify a derivation via 'field.type', but no value was present`,
field.type
);
assert(
`No '${field.type}' derivation registered for use by the '${kind}' field '${name}'`,
this._derivations.has(field.type)
);
return this._derivations.get(field.type)!;
}
hashFn(field: HashField | { type: string }): HashFn {
const kind = 'kind' in field ? field.kind : '<unknown kind>';
const name = 'name' in field ? field.name : '<unknown name>';
assert(
`The '${kind}' field '${name}' is not a HashField and so cannot be used to lookup a hash function`,
!('kind' in field) || kind === '@hash'
);
assert(
`Expected the '${kind}' field '${name}' to specify a hash function via 'field.type', but no value was present`,
field.type
);
assert(
`No '${field.type}' hash function is registered for use by the '${kind}' field '${name}'`,
this._hashFns.has(field.type)
);
return this._hashFns.get(field.type)!;
}
resource(resource: StableRecordIdentifier | { type: string }): ResourceSchema {
assert(`No resource registered with name '${resource.type}'`, this._schemas.has(resource.type));
return this._schemas.get(resource.type)!.original;
}
registerResources(schemas: ResourceSchema[]): void {
schemas.forEach((schema) => {
this.registerResource(schema);
});
}
registerResource(schema: ResourceSchema): void {
const fields = new Map<string, FieldSchema>();
const relationships: Record<string, LegacyRelationshipSchema> = {};
const attributes: Record<string, LegacyAttributeField> = {};
schema.fields.forEach((field) => {
assert(
`${field.kind} is not valid inside a ResourceSchema's fields.`,
// @ts-expect-error we are checking for mistakes at runtime
field.kind !== '@id' && field.kind !== '@hash'
);
fields.set(field.name, field);
if (field.kind === 'attribute') {
attributes[field.name] = field;
} else if (field.kind === 'belongsTo' || field.kind === 'hasMany') {
relationships[field.name] = field;
}
});
const traits = new Set<string>(schema.traits);
traits.forEach((trait) => {
this._traits.add(trait);
});
const internalSchema: InternalSchema = { original: schema, fields, relationships, attributes, traits };
this._schemas.set(schema.type, internalSchema);
}
registerTransformation<T extends Value = string, PT = unknown>(transformation: Transformation<T, PT>): void {
this._transforms.set(transformation[Type], transformation as Transformation);
}
registerDerivation<R, T, FM extends ObjectValue | null>(derivation: Derivation<R, T, FM>): void {
this._derivations.set(derivation[Type], makeCachedDerivation(derivation));
}
registerHashFn<T extends object>(hashFn: HashFn<T>): void {
this._hashFns.set(hashFn[Type], hashFn as HashFn);
}
fields({ type }: { type: string }): InternalSchema['fields'] {
const schema = this._schemas.get(type);
if (!schema) {
throw new Error(`No schema defined for ${type}`);
}
return schema.fields;
}
hasResource(resource: { type: string }): boolean {
return this._schemas.has(resource.type);
}
}
if (ENABLE_LEGACY_SCHEMA_SERVICE) {
SchemaService.prototype.attributesDefinitionFor = function ({
type,
}: {
type: string;
}): InternalSchema['attributes'] {
deprecate(`Use \`schema.fields({ type })\` instead of \`schema.attributesDefinitionFor({ type })\``, false, {
id: 'ember-data:schema-service-updates',
until: '6.0',
for: 'ember-data',
since: {
available: '4.13',
enabled: '5.4',
},
});
const schema = this._schemas.get(type);
if (!schema) {
throw new Error(`No schema defined for ${type}`);
}
return schema.attributes;
};
SchemaService.prototype.relationshipsDefinitionFor = function ({
type,
}: {
type: string;
}): InternalSchema['relationships'] {
deprecate(`Use \`schema.fields({ type })\` instead of \`schema.relationshipsDefinitionFor({ type })\``, false, {
id: 'ember-data:schema-service-updates',
until: '6.0',
for: 'ember-data',
since: {
available: '4.13',
enabled: '5.4',
},
});
const schema = this._schemas.get(type);
if (!schema) {
throw new Error(`No schema defined for ${type}`);
}
return schema.relationships;
};
SchemaService.prototype.doesTypeExist = function (type: string): boolean {
deprecate(`Use \`schema.hasResource({ type })\` instead of \`schema.doesTypeExist(type)\``, false, {
id: 'ember-data:schema-service-updates',
until: '6.0',
for: 'ember-data',
since: {
available: '4.13',
enabled: '5.4',
},
});
return this._schemas.has(type);
};
}