-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
payload.ts
793 lines (667 loc) · 24.2 KB
/
payload.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
import { Accountability, Query, SchemaOverview } from '@directus/shared/types';
import { format, parseISO, isValid } from 'date-fns';
import { parseJSON, toArray } from '@directus/shared/utils';
import { unflatten } from 'flat';
import Joi from 'joi';
import { Knex } from 'knex';
import { clone, cloneDeep, isNil, isObject, isPlainObject, omit, pick } from 'lodash';
import { v4 as uuid } from 'uuid';
import { parse as wktToGeoJSON } from 'wellknown';
import getDatabase from '../database';
import { getHelpers, Helpers } from '../database/helpers';
import { ForbiddenException, InvalidPayloadException } from '../exceptions';
import { AbstractServiceOptions, ActionEventParams, Alterations, Item, MutationOptions, PrimaryKey } from '../types';
import { generateHash } from '../utils/generate-hash';
import { ItemsService } from './items';
type Action = 'create' | 'read' | 'update';
type Transformers = {
[type: string]: (context: {
action: Action;
value: any;
payload: Partial<Item>;
accountability: Accountability | null;
specials: string[];
helpers: Helpers;
}) => Promise<any>;
};
/**
* Process a given payload for a collection to ensure the special fields (hash, uuid, date etc) are
* handled correctly.
*/
export class PayloadService {
accountability: Accountability | null;
knex: Knex;
helpers: Helpers;
collection: string;
schema: SchemaOverview;
constructor(collection: string, options: AbstractServiceOptions) {
this.accountability = options.accountability || null;
this.knex = options.knex || getDatabase();
this.helpers = getHelpers(this.knex);
this.collection = collection;
this.schema = options.schema;
return this;
}
public transformers: Transformers = {
async hash({ action, value }) {
if (!value) return;
if (action === 'create' || action === 'update') {
return await generateHash(String(value));
}
return value;
},
async uuid({ action, value }) {
if (action === 'create' && !value) {
return uuid();
}
return value;
},
async 'cast-boolean'({ action, value }) {
if (action === 'read') {
if (value === true || value === 1 || value === '1') {
return true;
} else if (value === false || value === 0 || value === '0') {
return false;
} else if (value === null || value === '') {
return null;
}
}
return value;
},
async 'cast-json'({ action, value }) {
if (action === 'read') {
if (typeof value === 'string') {
try {
return parseJSON(value);
} catch {
return value;
}
}
}
return value;
},
async conceal({ action, value }) {
if (action === 'read') return value ? '**********' : null;
return value;
},
async 'user-created'({ action, value, accountability }) {
if (action === 'create') return accountability?.user || null;
return value;
},
async 'user-updated'({ action, value, accountability }) {
if (action === 'update') return accountability?.user || null;
return value;
},
async 'role-created'({ action, value, accountability }) {
if (action === 'create') return accountability?.role || null;
return value;
},
async 'role-updated'({ action, value, accountability }) {
if (action === 'update') return accountability?.role || null;
return value;
},
async 'date-created'({ action, value, helpers }) {
if (action === 'create') return new Date(helpers.date.writeTimestamp(new Date().toISOString()));
return value;
},
async 'date-updated'({ action, value, helpers }) {
if (action === 'update') return new Date(helpers.date.writeTimestamp(new Date().toISOString()));
return value;
},
async 'cast-csv'({ action, value }) {
if (Array.isArray(value) === false && typeof value !== 'string') return;
if (action === 'read') {
if (Array.isArray(value)) return value;
if (value === '') return [];
return value.split(',');
}
if (Array.isArray(value)) {
return value.join(',');
}
return value;
},
};
processValues(action: Action, payloads: Partial<Item>[]): Promise<Partial<Item>[]>;
processValues(action: Action, payload: Partial<Item>): Promise<Partial<Item>>;
async processValues(
action: Action,
payload: Partial<Item> | Partial<Item>[]
): Promise<Partial<Item> | Partial<Item>[]> {
const processedPayload = toArray(payload);
if (processedPayload.length === 0) return [];
const fieldsInPayload = Object.keys(processedPayload[0]);
let specialFieldsInCollection = Object.entries(this.schema.collections[this.collection].fields).filter(
([_name, field]) => field.special && field.special.length > 0
);
if (action === 'read') {
specialFieldsInCollection = specialFieldsInCollection.filter(([name]) => {
return fieldsInPayload.includes(name);
});
}
await Promise.all(
processedPayload.map(async (record: any) => {
await Promise.all(
specialFieldsInCollection.map(async ([name, field]) => {
const newValue = await this.processField(field, record, action, this.accountability);
if (newValue !== undefined) record[name] = newValue;
})
);
})
);
this.processGeometries(processedPayload, action);
this.processDates(processedPayload, action);
if (['create', 'update'].includes(action)) {
processedPayload.forEach((record) => {
for (const [key, value] of Object.entries(record)) {
if (Array.isArray(value) || (typeof value === 'object' && !(value instanceof Date) && value !== null)) {
if (!value.isRawInstance) {
record[key] = JSON.stringify(value);
}
}
}
});
}
if (action === 'read') {
this.processAggregates(processedPayload);
}
if (Array.isArray(payload)) {
return processedPayload;
}
return processedPayload[0];
}
processAggregates(payload: Partial<Item>[]) {
const aggregateKeys = Object.keys(payload[0]).filter((key) => key.includes('->'));
if (aggregateKeys.length) {
for (const item of payload) {
Object.assign(item, unflatten(pick(item, aggregateKeys), { delimiter: '->' }));
aggregateKeys.forEach((key) => delete item[key]);
}
}
}
async processField(
field: SchemaOverview['collections'][string]['fields'][string],
payload: Partial<Item>,
action: Action,
accountability: Accountability | null
): Promise<any> {
if (!field.special) return payload[field.field];
const fieldSpecials = field.special ? toArray(field.special) : [];
let value = clone(payload[field.field]);
for (const special of fieldSpecials) {
if (special in this.transformers) {
value = await this.transformers[special]({
action,
value,
payload,
accountability,
specials: fieldSpecials,
helpers: this.helpers,
});
}
}
return value;
}
/**
* Native geometries are stored in custom binary format. We need to insert them with
* the function st_geomfromtext. For this to work, that function call must not be
* escaped. It's therefore placed as a Knex.Raw object in the payload. Thus the need
* to check if the value is a raw instance before stringifying it in the next step.
*/
processGeometries<T extends Partial<Record<string, any>>[]>(payloads: T, action: Action): T {
const process =
action == 'read'
? (value: any) => (typeof value === 'string' ? wktToGeoJSON(value) : value)
: (value: any) => this.helpers.st.fromGeoJSON(typeof value == 'string' ? parseJSON(value) : value);
const fieldsInCollection = Object.entries(this.schema.collections[this.collection].fields);
const geometryColumns = fieldsInCollection.filter(([_, field]) => field.type.startsWith('geometry'));
for (const [name] of geometryColumns) {
for (const payload of payloads) {
if (payload[name]) {
payload[name] = process(payload[name]);
}
}
}
return payloads;
}
/**
* Knex returns `datetime` and `date` columns as Date.. This is wrong for date / datetime, as those
* shouldn't return with time / timezone info respectively
*/
processDates(payloads: Partial<Record<string, any>>[], action: Action): Partial<Record<string, any>>[] {
const fieldsInCollection = Object.entries(this.schema.collections[this.collection].fields);
const dateColumns = fieldsInCollection.filter(([_name, field]) =>
['dateTime', 'date', 'timestamp'].includes(field.type)
);
const timeColumns = fieldsInCollection.filter(([_name, field]) => {
return field.type === 'time';
});
if (dateColumns.length === 0 && timeColumns.length === 0) return payloads;
for (const [name, dateColumn] of dateColumns) {
for (const payload of payloads) {
let value: number | string | Date = payload[name];
if (value === null || (typeof value === 'string' && /^[.0 :-]{10,}$/.test(value))) {
payload[name] = null;
continue;
}
if (!value) continue;
if (action === 'read') {
if (typeof value === 'number' || typeof value === 'string') {
value = new Date(value);
}
if (dateColumn.type === 'timestamp') {
const newValue = this.helpers.date.readTimestampString(value.toISOString());
payload[name] = newValue;
}
if (dateColumn.type === 'dateTime') {
const year = String(value.getFullYear());
const month = String(value.getMonth() + 1).padStart(2, '0');
const day = String(value.getDate()).padStart(2, '0');
const hours = String(value.getHours()).padStart(2, '0');
const minutes = String(value.getMinutes()).padStart(2, '0');
const seconds = String(value.getSeconds()).padStart(2, '0');
const newValue = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
payload[name] = newValue;
}
if (dateColumn.type === 'date') {
const year = String(value.getFullYear());
const month = String(value.getMonth() + 1).padStart(2, '0');
const day = String(value.getDate()).padStart(2, '0');
// Strip off the time / timezone information from a date-only value
const newValue = `${year}-${month}-${day}`;
payload[name] = newValue;
}
} else {
if (value instanceof Date === false && typeof value === 'string') {
if (dateColumn.type === 'date') {
const parsedDate = parseISO(value);
if (!isValid(parsedDate)) {
throw new InvalidPayloadException(`Invalid Date format in field "${dateColumn.field}"`);
}
payload[name] = parsedDate;
}
if (dateColumn.type === 'dateTime') {
const parsedDate = parseISO(value);
if (!isValid(parsedDate)) {
throw new InvalidPayloadException(`Invalid DateTime format in field "${dateColumn.field}"`);
}
payload[name] = parsedDate;
}
if (dateColumn.type === 'timestamp') {
const newValue = this.helpers.date.writeTimestamp(value);
payload[name] = newValue;
}
}
}
}
}
/**
* Some DB drivers (MS SQL f.e.) return time values as Date objects. For consistencies sake,
* we'll abstract those back to hh:mm:ss
*/
for (const [name] of timeColumns) {
for (const payload of payloads) {
const value = payload[name];
if (!value) continue;
if (action === 'read') {
if (value instanceof Date) payload[name] = format(value, 'HH:mm:ss');
}
}
}
return payloads;
}
/**
* Recursively save/update all nested related Any-to-One items
*/
async processA2O(
data: Partial<Item>,
opts?: MutationOptions
): Promise<{ payload: Partial<Item>; revisions: PrimaryKey[]; nestedActionEvents: ActionEventParams[] }> {
const relations = this.schema.relations.filter((relation) => {
return relation.collection === this.collection;
});
const revisions: PrimaryKey[] = [];
const nestedActionEvents: ActionEventParams[] = [];
const payload = cloneDeep(data);
// Only process related records that are actually in the payload
const relationsToProcess = relations.filter((relation) => {
return relation.field in payload && isPlainObject(payload[relation.field]);
});
for (const relation of relationsToProcess) {
// If the required a2o configuration fields are missing, this is a m2o instead of an a2o
if (!relation.meta?.one_collection_field || !relation.meta?.one_allowed_collections) continue;
const relatedCollection = payload[relation.meta.one_collection_field];
if (!relatedCollection) {
throw new InvalidPayloadException(
`Can't update nested record "${relation.collection}.${relation.field}" without field "${relation.collection}.${relation.meta.one_collection_field}" being set`
);
}
const allowedCollections = relation.meta.one_allowed_collections;
if (allowedCollections.includes(relatedCollection) === false) {
throw new InvalidPayloadException(
`"${relation.collection}.${relation.field}" can't be linked to collection "${relatedCollection}"`
);
}
const itemsService = new ItemsService(relatedCollection, {
accountability: this.accountability,
knex: this.knex,
schema: this.schema,
});
const relatedPrimary = this.schema.collections[relatedCollection].primary;
const relatedRecord: Partial<Item> = payload[relation.field];
if (['string', 'number'].includes(typeof relatedRecord)) continue;
const hasPrimaryKey = relatedPrimary in relatedRecord;
let relatedPrimaryKey: PrimaryKey = relatedRecord[relatedPrimary];
const exists =
hasPrimaryKey &&
!!(await this.knex
.select(relatedPrimary)
.from(relatedCollection)
.where({ [relatedPrimary]: relatedPrimaryKey })
.first());
if (exists) {
const fieldsToUpdate = omit(relatedRecord, relatedPrimary);
if (Object.keys(fieldsToUpdate).length > 0) {
await itemsService.updateOne(relatedPrimaryKey, relatedRecord, {
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
}
} else {
relatedPrimaryKey = await itemsService.createOne(relatedRecord, {
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
}
// Overwrite the nested object with just the primary key, so the parent level can be saved correctly
payload[relation.field] = relatedPrimaryKey;
}
return { payload, revisions, nestedActionEvents };
}
/**
* Save/update all nested related m2o items inside the payload
*/
async processM2O(
data: Partial<Item>,
opts?: MutationOptions
): Promise<{ payload: Partial<Item>; revisions: PrimaryKey[]; nestedActionEvents: ActionEventParams[] }> {
const payload = cloneDeep(data);
// All the revisions saved on this level
const revisions: PrimaryKey[] = [];
const nestedActionEvents: ActionEventParams[] = [];
// Many to one relations that exist on the current collection
const relations = this.schema.relations.filter((relation) => {
return relation.collection === this.collection;
});
// Only process related records that are actually in the payload
const relationsToProcess = relations.filter((relation) => {
return relation.field in payload && isObject(payload[relation.field]);
});
for (const relation of relationsToProcess) {
// If no "one collection" exists, this is a A2O, not a M2O
if (!relation.related_collection) continue;
const relatedPrimaryKeyField = this.schema.collections[relation.related_collection].primary;
// Items service to the related collection
const itemsService = new ItemsService(relation.related_collection, {
accountability: this.accountability,
knex: this.knex,
schema: this.schema,
});
const relatedRecord: Partial<Item> = payload[relation.field];
if (['string', 'number'].includes(typeof relatedRecord)) continue;
const hasPrimaryKey = relatedPrimaryKeyField in relatedRecord;
let relatedPrimaryKey: PrimaryKey = relatedRecord[relatedPrimaryKeyField];
const exists =
hasPrimaryKey &&
!!(await this.knex
.select(relatedPrimaryKeyField)
.from(relation.related_collection)
.where({ [relatedPrimaryKeyField]: relatedPrimaryKey })
.first());
if (exists) {
const fieldsToUpdate = omit(relatedRecord, relatedPrimaryKeyField);
if (Object.keys(fieldsToUpdate).length > 0) {
await itemsService.updateOne(relatedPrimaryKey, relatedRecord, {
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
}
} else {
relatedPrimaryKey = await itemsService.createOne(relatedRecord, {
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
}
// Overwrite the nested object with just the primary key, so the parent level can be saved correctly
payload[relation.field] = relatedPrimaryKey;
}
return { payload, revisions, nestedActionEvents };
}
/**
* Recursively save/update all nested related o2m items
*/
async processO2M(
data: Partial<Item>,
parent: PrimaryKey,
opts?: MutationOptions
): Promise<{ revisions: PrimaryKey[]; nestedActionEvents: ActionEventParams[] }> {
const revisions: PrimaryKey[] = [];
const nestedActionEvents: ActionEventParams[] = [];
const relations = this.schema.relations.filter((relation) => {
return relation.related_collection === this.collection;
});
const payload = cloneDeep(data);
// Only process related records that are actually in the payload
const relationsToProcess = relations.filter((relation) => {
if (!relation.meta?.one_field) return false;
return relation.meta.one_field in payload;
});
const nestedUpdateSchema = Joi.object({
create: Joi.array().items(Joi.object().unknown()),
update: Joi.array().items(Joi.object().unknown()),
delete: Joi.array().items(Joi.string(), Joi.number()),
});
for (const relation of relationsToProcess) {
if (!relation.meta) continue;
const currentPrimaryKeyField = this.schema.collections[relation.related_collection!].primary;
const relatedPrimaryKeyField = this.schema.collections[relation.collection].primary;
const itemsService = new ItemsService(relation.collection, {
accountability: this.accountability,
knex: this.knex,
schema: this.schema,
});
const recordsToUpsert: Partial<Item>[] = [];
const savedPrimaryKeys: PrimaryKey[] = [];
// Nested array of individual items
const field = payload[relation.meta!.one_field!];
if (!field || Array.isArray(field)) {
const updates = field || []; // treat falsey values as removing all children
for (let i = 0; i < updates.length; i++) {
const relatedRecord = updates[i];
let record = cloneDeep(relatedRecord);
if (typeof relatedRecord === 'string' || typeof relatedRecord === 'number') {
const existingRecord = await this.knex
.select(relatedPrimaryKeyField, relation.field)
.from(relation.collection)
.where({ [relatedPrimaryKeyField]: record })
.first();
if (!!existingRecord === false) {
throw new ForbiddenException();
}
// If the related item is already associated to the current item, and there's no
// other updates (which is indicated by the fact that this is just the PK, we can
// ignore updating this item. This makes sure we don't trigger any update logic
// for items that aren't actually being updated. NOTE: We use == here, as the
// primary key might be reported as a string instead of number, coming from the
// http route, and or a bigInteger in the DB
if (
isNil(existingRecord[relation.field]) === false &&
(existingRecord[relation.field] == parent ||
existingRecord[relation.field] == payload[currentPrimaryKeyField])
) {
savedPrimaryKeys.push(existingRecord[relatedPrimaryKeyField]);
continue;
}
record = {
[relatedPrimaryKeyField]: relatedRecord,
};
}
recordsToUpsert.push({
...record,
[relation.field]: parent || payload[currentPrimaryKeyField],
});
}
savedPrimaryKeys.push(
...(await itemsService.upsertMany(recordsToUpsert, {
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
}))
);
const query: Query = {
filter: {
_and: [
{
[relation.field]: {
_eq: parent,
},
},
{
[relatedPrimaryKeyField]: {
_nin: savedPrimaryKeys,
},
},
],
},
};
// Nullify all related items that aren't included in the current payload
if (relation.meta.one_deselect_action === 'delete') {
// There's no revision for a deletion
await itemsService.deleteByQuery(query, {
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
} else {
await itemsService.updateByQuery(
query,
{ [relation.field]: null },
{
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
}
);
}
}
// "Updates" object w/ create/update/delete
else {
const alterations = field as Alterations;
const { error } = nestedUpdateSchema.validate(alterations);
if (error) throw new InvalidPayloadException(`Invalid one-to-many update structure: ${error.message}`);
if (alterations.create) {
const sortField = relation.meta.sort_field;
let createPayload: Alterations['create'];
if (sortField !== null) {
const highestOrderNumber: Record<'max', number | null> | undefined = await this.knex
.from(relation.collection)
.where({ [relation.field]: parent })
.whereNotNull(sortField)
.max(sortField, { as: 'max' })
.first();
createPayload = alterations.create.map((item, index) => {
const record = cloneDeep(item);
// add sort field value if it is not supplied in the item
if (parent !== null && record[sortField] === undefined) {
record[sortField] = highestOrderNumber?.max ? highestOrderNumber.max + index + 1 : index + 1;
}
return {
...record,
[relation.field]: parent || payload[currentPrimaryKeyField],
};
});
} else {
createPayload = alterations.create.map((item) => ({
...item,
[relation.field]: parent || payload[currentPrimaryKeyField],
}));
}
await itemsService.createMany(createPayload, {
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
}
if (alterations.update) {
const primaryKeyField = this.schema.collections[relation.collection].primary;
for (const item of alterations.update) {
await itemsService.updateOne(
item[primaryKeyField],
{
...item,
[relation.field]: parent || payload[currentPrimaryKeyField],
},
{
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
}
);
}
}
if (alterations.delete) {
const query: Query = {
filter: {
_and: [
{
[relation.field]: {
_eq: parent,
},
},
{
[relatedPrimaryKeyField]: {
_in: alterations.delete,
},
},
],
},
};
if (relation.meta.one_deselect_action === 'delete') {
await itemsService.deleteByQuery(query, {
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
});
} else {
await itemsService.updateByQuery(
query,
{ [relation.field]: null },
{
onRevisionCreate: (pk) => revisions.push(pk),
bypassEmitAction: (params) => nestedActionEvents.push(params),
emitEvents: opts?.emitEvents,
}
);
}
}
}
}
return { revisions, nestedActionEvents };
}
/**
* Transforms the input partial payload to match the output structure, to have consistency
* between delta and data
*/
async prepareDelta(data: Partial<Item>): Promise<string | null> {
let payload = cloneDeep(data);
for (const key in payload) {
if (payload[key]?.isRawInstance) {
payload[key] = payload[key].bindings[0];
}
}
payload = await this.processValues('read', payload);
if (Object.keys(payload).length === 0) return null;
return JSON.stringify(payload);
}
}