@visiblevc/ember-api-mocks 0.0.0-stage → 0.1.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/src/store.ts ADDED
@@ -0,0 +1,214 @@
1
+ import { getContext } from '@ember/test-helpers';
2
+ import {
3
+ dependencySatisfies,
4
+ importSync,
5
+ macroCondition,
6
+ } from '@embroider/macros';
7
+
8
+ import {
9
+ build,
10
+ buildList,
11
+ documentFor,
12
+ definitionOf,
13
+ factoryOf,
14
+ overridesOf,
15
+ transientOf,
16
+ } from './factories.ts';
17
+ import type { Attrs, BuiltRecord } from './formats.ts';
18
+
19
+ /* Minimal structural types so the addon works with ember-data 4.12 and 5.x */
20
+ interface ModelClass {
21
+ prototype: object;
22
+ eachAttribute(callback: (name: string) => void): void;
23
+ eachComputedProperty?(
24
+ callback: (name: string, meta: { isAttribute?: boolean } | null) => void,
25
+ ): void;
26
+ eachRelationship(
27
+ callback: (name: string, meta: { kind: string }) => void,
28
+ ): void;
29
+ }
30
+
31
+ interface Serializer {
32
+ attrs?: Record<string, string | { key?: string }>;
33
+ keyForAttribute(name: string, method: string): string;
34
+ keyForRelationship(name: string, kind: string, method: string): string;
35
+ }
36
+
37
+ interface Store {
38
+ modelFor(name: string): ModelClass;
39
+ serializerFor(name: string): Serializer & {
40
+ normalize(
41
+ modelClass: ModelClass,
42
+ hash: Attrs,
43
+ ): { data: { attributes: Attrs } };
44
+ };
45
+ pushPayload(name: string, payload: unknown): void;
46
+ peekRecord(name: string, id: string): unknown;
47
+ createFragment?(name: string, attributes: Attrs): Attrs;
48
+ }
49
+
50
+ const sources = new WeakMap<object, BuiltRecord>();
51
+
52
+ function isFragment(modelClass: ModelClass): boolean {
53
+ if (macroCondition(dependencySatisfies('ember-data-model-fragments', '*'))) {
54
+ const { default: Fragment } = importSync(
55
+ 'ember-data-model-fragments/fragment',
56
+ ) as { default: abstract new () => object };
57
+ return modelClass.prototype instanceof Fragment;
58
+ }
59
+ return false;
60
+ }
61
+
62
+ function attributeKeys(
63
+ serializer: Serializer,
64
+ modelClass: ModelClass,
65
+ ): Set<string> {
66
+ const keys = new Set(['id']);
67
+ const add = (attribute: string) => {
68
+ keys.add(attribute);
69
+ keys.add(serializer.keyForAttribute(attribute, 'deserialize'));
70
+ };
71
+ modelClass.eachAttribute(add);
72
+ modelClass.eachComputedProperty?.((name, meta) => {
73
+ if (meta?.isAttribute) {
74
+ add(name);
75
+ }
76
+ });
77
+ return keys;
78
+ }
79
+
80
+ function modelKeys(
81
+ serializer: Serializer,
82
+ modelClass: ModelClass,
83
+ ): { keys: Set<string>; relationships: Set<string> } {
84
+ const keys = attributeKeys(serializer, modelClass);
85
+ const relationships = new Set<string>();
86
+ modelClass.eachRelationship((relationship, { kind }) => {
87
+ const key = serializer.keyForRelationship(
88
+ relationship,
89
+ kind,
90
+ 'deserialize',
91
+ );
92
+ relationships.add(key);
93
+ keys.add(key);
94
+ keys.add(`${key.replace(/_ids?$/, '')}_type`);
95
+ });
96
+ for (const [name, mapping] of Object.entries(serializer.attrs ?? {})) {
97
+ keys.add(serializer.keyForAttribute(name, 'deserialize'));
98
+ const key = typeof mapping === 'string' ? mapping : mapping.key;
99
+ if (key) {
100
+ keys.add(key);
101
+ }
102
+ }
103
+ return { keys, relationships };
104
+ }
105
+
106
+ function rejectUnusedOverrides(
107
+ name: string,
108
+ record: BuiltRecord,
109
+ { keys, relationships }: ReturnType<typeof modelKeys>,
110
+ ): void {
111
+ const overrides = overridesOf(record);
112
+ const undeclared = overrides.find(
113
+ ({ key, relationship }) => !relationship && relationships.has(key),
114
+ );
115
+ if (undeclared && definitionOf(name).format.separatesRelationships) {
116
+ throw new Error(
117
+ `seed('${name}') got ${undeclared.key}, a relationship the ${name} factory does not declare. Declare it in the factory's relationships: { ${undeclared.key}: belongsTo(...) } or hasMany(...).`,
118
+ );
119
+ }
120
+ const unused = overrides
121
+ .map(({ key }) => key)
122
+ .filter((key) => !keys.has(key));
123
+ if (unused.length) {
124
+ throw new Error(
125
+ `seed('${name}') got ${unused.join(', ')}, which the ${name} model does not read. Use the keys the API sends.`,
126
+ );
127
+ }
128
+ }
129
+
130
+ function currentStore(): Store {
131
+ const context = getContext() as
132
+ { owner?: { lookup(name: string): unknown } } | undefined;
133
+ if (!context?.owner) {
134
+ throw new Error(
135
+ 'seed() needs a test set up with setupTest or setupRenderingTest',
136
+ );
137
+ }
138
+ return context.owner.lookup('service:store') as Store;
139
+ }
140
+
141
+ function pushFragment(
142
+ store: Store,
143
+ name: string,
144
+ modelClass: ModelClass,
145
+ record: BuiltRecord,
146
+ ): unknown {
147
+ const serializer = store.serializerFor(name);
148
+ const { id: _id, ...attrs } = record;
149
+ const { data } = serializer.normalize(modelClass, attrs);
150
+ const fragment = store.createFragment!(name, data.attributes);
151
+ const known = attributeKeys(serializer, modelClass);
152
+ for (const [key, value] of Object.entries(attrs)) {
153
+ if (!known.has(key)) {
154
+ fragment[key] = value;
155
+ }
156
+ }
157
+ return fragment;
158
+ }
159
+
160
+ function push(name: string, record: BuiltRecord): unknown {
161
+ const store = currentStore();
162
+ const modelClass = store.modelFor(name);
163
+ if (isFragment(modelClass)) {
164
+ return pushFragment(store, name, modelClass, record);
165
+ }
166
+ rejectUnusedOverrides(
167
+ name,
168
+ record,
169
+ modelKeys(store.serializerFor(name), modelClass),
170
+ );
171
+ const { beforeSeed, afterSeed } = definitionOf(name);
172
+ beforeSeed?.(record, store);
173
+ store.pushPayload(
174
+ name,
175
+ JSON.parse(JSON.stringify(documentFor(name, record, {}, true))),
176
+ );
177
+ const model = store.peekRecord(name, String(record.id)) as object;
178
+ sources.set(model, record);
179
+ afterSeed?.(model, transientOf(record));
180
+ return model;
181
+ }
182
+
183
+ export function seed<T = unknown>(
184
+ name: string,
185
+ ...args: Array<string | Attrs>
186
+ ): T {
187
+ return push(name, build(name, ...args)) as T;
188
+ }
189
+
190
+ export function seedList<T = unknown>(name: string, ...args: unknown[]): T[] {
191
+ return buildList(name, ...args).map((record) => push(name, record) as T);
192
+ }
193
+
194
+ export function seedRecord<T = unknown>(record: object): T {
195
+ const name = factoryOf(record);
196
+ if (!name) {
197
+ throw new Error('seedRecord() takes a record from build()');
198
+ }
199
+ return push(name, record as BuiltRecord) as T;
200
+ }
201
+
202
+ export function sourceOf(value: unknown): unknown {
203
+ if (value !== null && typeof value === 'object' && sources.has(value)) {
204
+ return sources.get(value);
205
+ }
206
+ const modelName = (value as { constructor?: { modelName?: unknown } } | null)
207
+ ?.constructor?.modelName;
208
+ if (typeof modelName === 'string') {
209
+ throw new Error(
210
+ `A ${modelName} record that was not created with seed() was used in a mocked response. Pass API JSON instead.`,
211
+ );
212
+ }
213
+ return value;
214
+ }