-
-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathnested-write-visitor.ts
More file actions
355 lines (315 loc) · 13.1 KB
/
Copy pathnested-write-visitor.ts
File metadata and controls
355 lines (315 loc) · 13.1 KB
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import { enumerate } from '@zenstackhq/common-helpers';
import type { FieldDef, SchemaDef } from '@zenstackhq/schema';
import { ORMWriteActions, type MaybePromise, type ORMWriteActionType } from './types';
type NestingPathItem = { field?: FieldDef; model: string; where: any; unique: boolean };
/**
* Context for visiting
*/
export type NestedWriteVisitorContext = {
/**
* Parent data, can be used to replace fields
*/
parent: any;
/**
* Current field, undefined if toplevel
*/
field?: FieldDef;
/**
* A top-down path of all nested update conditions and corresponding field till now
*/
nestingPath: NestingPathItem[];
};
/**
* NestedWriteVisitor's callback actions. A call back function should return true or void to indicate
* that the visitor should continue traversing its children, or false to stop. It can also return an object
* to let the visitor traverse it instead of its original children.
*/
export type NestedWriteVisitorCallback = {
create?: (model: string, data: any, context: NestedWriteVisitorContext) => MaybePromise<boolean | object | void>;
createMany?: (
model: string,
args: { data: any; skipDuplicates?: boolean },
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
connectOrCreate?: (
model: string,
args: { where: object; create: any },
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
connect?: (
model: string,
args: object,
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
disconnect?: (
model: string,
args: object,
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
set?: (model: string, args: object, context: NestedWriteVisitorContext) => MaybePromise<boolean | object | void>;
update?: (model: string, args: object, context: NestedWriteVisitorContext) => MaybePromise<boolean | object | void>;
updateMany?: (
model: string,
args: { where?: object; data: any },
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
upsert?: (
model: string,
args: { where: object; create: any; update: any },
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
delete?: (
model: string,
args: object | boolean,
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
deleteMany?: (
model: string,
args: any | object,
context: NestedWriteVisitorContext,
) => MaybePromise<boolean | object | void>;
field?: (
field: FieldDef,
action: ORMWriteActionType,
data: any,
context: NestedWriteVisitorContext,
) => MaybePromise<void>;
};
/**
* Recursive visitor for nested write (create/update) payload.
*/
export class NestedWriteVisitor {
constructor(
private readonly schema: SchemaDef,
private readonly callback: NestedWriteVisitorCallback,
) {}
private isWriteAction(value: string): value is ORMWriteActionType {
return ORMWriteActions.includes(value as ORMWriteActionType);
}
/**
* Start visiting
*
* @see NestedWriteVisitorCallback
*/
async visit(model: string, action: ORMWriteActionType, args: any): Promise<void> {
if (!args) {
return;
}
let topData = args;
switch (action) {
// create has its data wrapped in 'data' field
case 'create':
topData = topData.data;
break;
case 'delete':
case 'deleteMany':
topData = topData.where;
break;
}
await this.doVisit(model, action, topData, undefined, undefined, []);
}
private async doVisit(
model: string,
action: ORMWriteActionType,
data: any,
parent: any,
field: FieldDef | undefined,
nestingPath: NestingPathItem[],
): Promise<void> {
if (!data) {
return;
}
const toplevel = field == undefined;
const context = { parent, field, nestingPath: [...nestingPath] };
const pushNewContext = (field: FieldDef | undefined, model: string, where: any, unique = false) => {
return { ...context, nestingPath: [...context.nestingPath, { field, model, where, unique }] };
};
// visit payload
switch (action) {
case 'create':
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, {});
let callbackResult: any;
if (this.callback.create) {
callbackResult = await this.callback.create(model, item, newContext);
}
if (callbackResult !== false) {
const subPayload = typeof callbackResult === 'object' ? callbackResult : item;
await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
}
}
break;
case 'createMany':
case 'createManyAndReturn':
{
const newContext = pushNewContext(field, model, {});
let callbackResult: any;
if (this.callback.createMany) {
callbackResult = await this.callback.createMany(model, data, newContext);
}
if (callbackResult !== false) {
const subPayload = typeof callbackResult === 'object' ? callbackResult : data.data;
await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
}
}
break;
case 'connectOrCreate':
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item.where);
let callbackResult: any;
if (this.callback.connectOrCreate) {
callbackResult = await this.callback.connectOrCreate(model, item, newContext);
}
if (callbackResult !== false) {
const subPayload = typeof callbackResult === 'object' ? callbackResult : item.create;
await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
}
}
break;
case 'connect':
if (this.callback.connect) {
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item, true);
await this.callback.connect(model, item, newContext);
}
}
break;
case 'disconnect':
// disconnect has two forms:
// if relation is to-many, the payload is a unique filter object
// if relation is to-one, the payload can only be boolean `true`
if (this.callback.disconnect) {
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item, typeof item === 'object');
await this.callback.disconnect(model, item, newContext);
}
}
break;
case 'set':
if (this.callback.set) {
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item, true);
await this.callback.set(model, item, newContext);
}
}
break;
case 'update':
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item.where);
let callbackResult: any;
if (this.callback.update) {
callbackResult = await this.callback.update(model, item, newContext);
}
if (callbackResult !== false) {
const subPayload =
typeof callbackResult === 'object'
? callbackResult
: typeof item.data === 'object'
? item.data
: item;
await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
}
}
break;
case 'updateMany':
case 'updateManyAndReturn':
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item.where);
let callbackResult: any;
if (this.callback.updateMany) {
callbackResult = await this.callback.updateMany(model, item, newContext);
}
if (callbackResult !== false) {
const subPayload = typeof callbackResult === 'object' ? callbackResult : item;
await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
}
}
break;
case 'upsert': {
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, item.where);
let callbackResult: any;
if (this.callback.upsert) {
callbackResult = await this.callback.upsert(model, item, newContext);
}
if (callbackResult !== false) {
if (typeof callbackResult === 'object') {
await this.visitSubPayload(model, action, callbackResult, newContext.nestingPath);
} else {
await this.visitSubPayload(model, action, item.create, newContext.nestingPath);
await this.visitSubPayload(model, action, item.update, newContext.nestingPath);
}
}
}
break;
}
case 'delete': {
if (this.callback.delete) {
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, toplevel ? item.where : item);
await this.callback.delete(model, item, newContext);
}
}
break;
}
case 'deleteMany':
if (this.callback.deleteMany) {
for (const item of this.enumerateReverse(data)) {
const newContext = pushNewContext(field, model, toplevel ? item.where : item);
await this.callback.deleteMany(model, item, newContext);
}
}
break;
}
}
private async visitSubPayload(
model: string,
action: ORMWriteActionType,
payload: any,
nestingPath: NestingPathItem[],
) {
for (const item of enumerate(payload)) {
if (!item || typeof item !== 'object') {
continue;
}
for (const field of Object.keys(item)) {
const fieldDef = this.schema.models[model]?.fields[field];
if (!fieldDef) {
continue;
}
if (fieldDef.relation) {
if (item[field]) {
// recurse into nested payloads
for (const [subAction, subData] of Object.entries<any>(item[field])) {
if (this.isWriteAction(subAction) && subData) {
await this.doVisit(fieldDef.type, subAction, subData, item[field], fieldDef, [
...nestingPath,
]);
}
}
}
} else {
// visit plain field
if (this.callback.field) {
await this.callback.field(fieldDef, action, item[field], {
parent: item,
nestingPath,
field: fieldDef,
});
}
}
}
}
}
// enumerate a (possible) array in reverse order, so that the enumeration
// callback can safely delete the current item
private *enumerateReverse(data: any) {
if (Array.isArray(data)) {
for (let i = data.length - 1; i >= 0; i--) {
yield data[i];
}
} else {
yield data;
}
}
}