-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
items.ts
902 lines (762 loc) · 27.4 KB
/
items.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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
import { Accountability, Action, PermissionsAction, Query, SchemaOverview } from '@directus/shared/types';
import Keyv from 'keyv';
import { Knex } from 'knex';
import { assign, clone, cloneDeep, omit, pick, without } from 'lodash';
import { getCache } from '../cache';
import getDatabase from '../database';
import runAST from '../database/run-ast';
import emitter from '../emitter';
import env from '../env';
import { ForbiddenException, InvalidPayloadException } from '../exceptions';
import { translateDatabaseError } from '../exceptions/database/translate';
import {
AbstractService,
AbstractServiceOptions,
ActionEventParams,
Item as AnyItem,
MutationOptions,
PrimaryKey,
} from '../types';
import getASTFromQuery from '../utils/get-ast-from-query';
import { validateKeys } from '../utils/validate-keys';
import { AuthorizationService } from './authorization';
import { ActivityService, RevisionsService } from './index';
import { PayloadService } from './payload';
export type QueryOptions = {
stripNonRequested?: boolean;
permissionsAction?: PermissionsAction;
emitEvents?: boolean;
};
export class ItemsService<Item extends AnyItem = AnyItem> implements AbstractService {
collection: string;
knex: Knex;
accountability: Accountability | null;
eventScope: string;
schema: SchemaOverview;
cache: Keyv<any> | null;
constructor(collection: string, options: AbstractServiceOptions) {
this.collection = collection;
this.knex = options.knex || getDatabase();
this.accountability = options.accountability || null;
this.eventScope = this.collection.startsWith('directus_') ? this.collection.substring(9) : 'items';
this.schema = options.schema;
this.cache = getCache().cache;
return this;
}
async getKeysByQuery(query: Query): Promise<PrimaryKey[]> {
const primaryKeyField = this.schema.collections[this.collection].primary;
const readQuery = cloneDeep(query);
readQuery.fields = [primaryKeyField];
// Allow unauthenticated access
const itemsService = new ItemsService(this.collection, {
knex: this.knex,
schema: this.schema,
});
// We read the IDs of the items based on the query, and then run `updateMany`. `updateMany` does it's own
// permissions check for the keys, so we don't have to make this an authenticated read
const items = await itemsService.readByQuery(readQuery);
return items.map((item: AnyItem) => item[primaryKeyField]).filter((pk) => pk);
}
/**
* Create a single new item.
*/
async createOne(data: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey> {
const primaryKeyField = this.schema.collections[this.collection].primary;
const fields = Object.keys(this.schema.collections[this.collection].fields);
const aliases = Object.values(this.schema.collections[this.collection].fields)
.filter((field) => field.alias === true)
.map((field) => field.field);
const payload: AnyItem = cloneDeep(data);
const nestedActionEvents: ActionEventParams[] = [];
// By wrapping the logic in a transaction, we make sure we automatically roll back all the
// changes in the DB if any of the parts contained within throws an error. This also means
// that any errors thrown in any nested relational changes will bubble up and cancel the whole
// update tree
const primaryKey: PrimaryKey = await this.knex.transaction(async (trx) => {
// We're creating new services instances so they can use the transaction as their Knex interface
const payloadService = new PayloadService(this.collection, {
accountability: this.accountability,
knex: trx,
schema: this.schema,
});
const authorizationService = new AuthorizationService({
accountability: this.accountability,
knex: trx,
schema: this.schema,
});
// Run all hooks that are attached to this event so the end user has the chance to augment the
// item that is about to be saved
const payloadAfterHooks =
opts?.emitEvents !== false
? await emitter.emitFilter(
this.eventScope === 'items'
? ['items.create', `${this.collection}.items.create`]
: `${this.eventScope}.create`,
payload,
{
collection: this.collection,
},
{
database: trx,
schema: this.schema,
accountability: this.accountability,
}
)
: payload;
const payloadWithPresets = this.accountability
? await authorizationService.validatePayload('create', this.collection, payloadAfterHooks)
: payloadAfterHooks;
const {
payload: payloadWithM2O,
revisions: revisionsM2O,
nestedActionEvents: nestedActionEventsM2O,
} = await payloadService.processM2O(payloadWithPresets, opts);
const {
payload: payloadWithA2O,
revisions: revisionsA2O,
nestedActionEvents: nestedActionEventsA2O,
} = await payloadService.processA2O(payloadWithM2O, opts);
const payloadWithoutAliases = pick(payloadWithA2O, without(fields, ...aliases));
const payloadWithTypeCasting = await payloadService.processValues('create', payloadWithoutAliases);
// In case of manual string / UUID primary keys, the PK already exists in the object we're saving.
let primaryKey = payloadWithTypeCasting[primaryKeyField];
try {
const result = await trx
.insert(payloadWithoutAliases)
.into(this.collection)
.returning(primaryKeyField)
.then((result) => result[0]);
const returnedKey = typeof result === 'object' ? result[primaryKeyField] : result;
primaryKey = primaryKey ?? returnedKey;
} catch (err: any) {
throw await translateDatabaseError(err);
}
// Most database support returning, those who don't tend to return the PK anyways
// (MySQL/SQLite). In case the primary key isn't know yet, we'll do a best-attempt at
// fetching it based on the last inserted row
if (!primaryKey) {
// Fetching it with max should be safe, as we're in the context of the current transaction
const result = await trx.max(primaryKeyField, { as: 'id' }).from(this.collection).first();
primaryKey = result.id;
// Set the primary key on the input item, in order for the "after" event hook to be able
// to read from it
payload[primaryKeyField] = primaryKey;
}
const { revisions: revisionsO2M, nestedActionEvents: nestedActionEventsO2M } = await payloadService.processO2M(
payload,
primaryKey,
opts
);
nestedActionEvents.push(...nestedActionEventsM2O);
nestedActionEvents.push(...nestedActionEventsA2O);
nestedActionEvents.push(...nestedActionEventsO2M);
// If this is an authenticated action, and accountability tracking is enabled, save activity row
if (this.accountability && this.schema.collections[this.collection].accountability !== null) {
const activityService = new ActivityService({
knex: trx,
schema: this.schema,
});
const activity = await activityService.createOne({
action: Action.CREATE,
user: this.accountability!.user,
collection: this.collection,
ip: this.accountability!.ip,
user_agent: this.accountability!.userAgent,
origin: this.accountability!.origin,
item: primaryKey,
});
// If revisions are tracked, create revisions record
if (this.schema.collections[this.collection].accountability === 'all') {
const revisionsService = new RevisionsService({
knex: trx,
schema: this.schema,
});
const revision = await revisionsService.createOne({
activity: activity,
collection: this.collection,
item: primaryKey,
data: await payloadService.prepareDelta(payload),
delta: await payloadService.prepareDelta(payload),
});
// Make sure to set the parent field of the child-revision rows
const childrenRevisions = [...revisionsM2O, ...revisionsA2O, ...revisionsO2M];
if (childrenRevisions.length > 0) {
await revisionsService.updateMany(childrenRevisions, { parent: revision });
}
if (opts?.onRevisionCreate) {
opts.onRevisionCreate(revision);
}
}
}
return primaryKey;
});
if (opts?.emitEvents !== false) {
const actionEvent = {
event:
this.eventScope === 'items'
? ['items.create', `${this.collection}.items.create`]
: `${this.eventScope}.create`,
meta: {
payload,
key: primaryKey,
collection: this.collection,
},
context: {
database: getDatabase(),
schema: this.schema,
accountability: this.accountability,
},
};
if (!opts?.bypassEmitAction) {
emitter.emitAction(actionEvent.event, actionEvent.meta, actionEvent.context);
} else {
opts.bypassEmitAction(actionEvent);
}
for (const nestedActionEvent of nestedActionEvents) {
emitter.emitAction(nestedActionEvent.event, nestedActionEvent.meta, nestedActionEvent.context);
}
}
if (this.cache && env.CACHE_AUTO_PURGE && opts?.autoPurgeCache !== false) {
await this.cache.clear();
}
return primaryKey;
}
/**
* Create multiple new items at once. Inserts all provided records sequentially wrapped in a transaction.
*/
async createMany(data: Partial<Item>[], opts?: MutationOptions): Promise<PrimaryKey[]> {
const { primaryKeys, nestedActionEvents } = await this.knex.transaction(async (trx) => {
const service = new ItemsService(this.collection, {
accountability: this.accountability,
schema: this.schema,
knex: trx,
});
const primaryKeys: PrimaryKey[] = [];
const nestedActionEvents: ActionEventParams[] = [];
for (const payload of data) {
const primaryKey = await service.createOne(payload, {
...(opts || {}),
autoPurgeCache: false,
bypassEmitAction: (params) =>
opts?.bypassEmitAction ? opts.bypassEmitAction(params) : nestedActionEvents.push(params),
});
primaryKeys.push(primaryKey);
}
return { primaryKeys, nestedActionEvents };
});
if (opts?.emitEvents !== false) {
for (const nestedActionEvent of nestedActionEvents) {
if (!opts?.bypassEmitAction) {
emitter.emitAction(nestedActionEvent.event, nestedActionEvent.meta, nestedActionEvent.context);
} else {
opts.bypassEmitAction(nestedActionEvent);
}
}
}
if (this.cache && env.CACHE_AUTO_PURGE && opts?.autoPurgeCache !== false) {
await this.cache.clear();
}
return primaryKeys;
}
/**
* Get items by query
*/
async readByQuery(query: Query, opts?: QueryOptions): Promise<Item[]> {
const updatedQuery =
opts?.emitEvents !== false
? await emitter.emitFilter(
this.eventScope === 'items'
? ['items.query', `${this.collection}.items.query`]
: `${this.eventScope}.query`,
query,
{
collection: this.collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
)
: query;
let ast = await getASTFromQuery(this.collection, updatedQuery, this.schema, {
accountability: this.accountability,
// By setting the permissions action, you can read items using the permissions for another
// operation's permissions. This is used to dynamically check if you have update/delete
// access to (a) certain item(s)
action: opts?.permissionsAction || 'read',
knex: this.knex,
});
if (this.accountability && this.accountability.admin !== true) {
const authorizationService = new AuthorizationService({
accountability: this.accountability,
knex: this.knex,
schema: this.schema,
});
ast = await authorizationService.processAST(ast, opts?.permissionsAction);
}
const records = await runAST(ast, this.schema, {
knex: this.knex,
// GraphQL requires relational keys to be returned regardless
stripNonRequested: opts?.stripNonRequested !== undefined ? opts.stripNonRequested : true,
});
if (records === null) {
throw new ForbiddenException();
}
const filteredRecords =
opts?.emitEvents !== false
? await emitter.emitFilter(
this.eventScope === 'items' ? ['items.read', `${this.collection}.items.read`] : `${this.eventScope}.read`,
records,
{
query: updatedQuery,
collection: this.collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
)
: records;
if (opts?.emitEvents !== false) {
emitter.emitAction(
this.eventScope === 'items' ? ['items.read', `${this.collection}.items.read`] : `${this.eventScope}.read`,
{
payload: filteredRecords,
query: updatedQuery,
collection: this.collection,
},
{
database: this.knex || getDatabase(),
schema: this.schema,
accountability: this.accountability,
}
);
}
return filteredRecords as Item[];
}
/**
* Get single item by primary key
*/
async readOne(key: PrimaryKey, query: Query = {}, opts?: QueryOptions): Promise<Item> {
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, key);
const filterWithKey = assign({}, query.filter, { [primaryKeyField]: { _eq: key } });
const queryWithKey = assign({}, query, { filter: filterWithKey });
const results = await this.readByQuery(queryWithKey, opts);
if (results.length === 0) {
throw new ForbiddenException();
}
return results[0];
}
/**
* Get multiple items by primary keys
*/
async readMany(keys: PrimaryKey[], query: Query = {}, opts?: QueryOptions): Promise<Item[]> {
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, keys);
const filterWithKey = { _and: [{ [primaryKeyField]: { _in: keys } }, query.filter ?? {}] };
const queryWithKey = assign({}, query, { filter: filterWithKey });
// Set query limit as the number of keys
if (Array.isArray(keys) && keys.length > 0 && !queryWithKey.limit) {
queryWithKey.limit = keys.length;
}
const results = await this.readByQuery(queryWithKey, opts);
return results;
}
/**
* Update multiple items by query
*/
async updateByQuery(query: Query, data: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey[]> {
const keys = await this.getKeysByQuery(query);
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, keys);
return keys.length ? await this.updateMany(keys, data, opts) : [];
}
/**
* Update a single item by primary key
*/
async updateOne(key: PrimaryKey, data: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey> {
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, key);
await this.updateMany([key], data, opts);
return key;
}
/**
* Update multiple items in a single transaction
*/
async updateBatch(data: Partial<Item>[], opts?: MutationOptions): Promise<PrimaryKey[]> {
if (!Array.isArray(data)) {
throw new InvalidPayloadException('Input should be an array of items.');
}
const primaryKeyField = this.schema.collections[this.collection].primary;
const keys: PrimaryKey[] = [];
try {
await this.knex.transaction(async (trx) => {
const service = new ItemsService(this.collection, {
accountability: this.accountability,
knex: trx,
schema: this.schema,
});
for (const item of data) {
if (!item[primaryKeyField]) throw new InvalidPayloadException(`Item in update misses primary key.`);
const combinedOpts = Object.assign({ autoPurgeCache: false }, opts);
keys.push(await service.updateOne(item[primaryKeyField]!, omit(item, primaryKeyField), combinedOpts));
}
});
} finally {
if (this.cache && env.CACHE_AUTO_PURGE && opts?.autoPurgeCache !== false) {
await this.cache.clear();
}
}
return keys;
}
/**
* Update many items by primary key, setting all items to the same change
*/
async updateMany(keys: PrimaryKey[], data: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey[]> {
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, keys);
const fields = Object.keys(this.schema.collections[this.collection].fields);
const aliases = Object.values(this.schema.collections[this.collection].fields)
.filter((field) => field.alias === true)
.map((field) => field.field);
const payload: Partial<AnyItem> = cloneDeep(data);
const nestedActionEvents: ActionEventParams[] = [];
const authorizationService = new AuthorizationService({
accountability: this.accountability,
knex: this.knex,
schema: this.schema,
});
// Run all hooks that are attached to this event so the end user has the chance to augment the
// item that is about to be saved
const payloadAfterHooks =
opts?.emitEvents !== false
? await emitter.emitFilter(
this.eventScope === 'items'
? ['items.update', `${this.collection}.items.update`]
: `${this.eventScope}.update`,
payload,
{
keys,
collection: this.collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
)
: payload;
// Sort keys to ensure that the order is maintained
keys.sort();
if (this.accountability) {
await authorizationService.checkAccess('update', this.collection, keys);
}
const payloadWithPresets = this.accountability
? await authorizationService.validatePayload('update', this.collection, payloadAfterHooks)
: payloadAfterHooks;
await this.knex.transaction(async (trx) => {
const payloadService = new PayloadService(this.collection, {
accountability: this.accountability,
knex: trx,
schema: this.schema,
});
const {
payload: payloadWithM2O,
revisions: revisionsM2O,
nestedActionEvents: nestedActionEventsM2O,
} = await payloadService.processM2O(payloadWithPresets, opts);
const {
payload: payloadWithA2O,
revisions: revisionsA2O,
nestedActionEvents: nestedActionEventsA2O,
} = await payloadService.processA2O(payloadWithM2O, opts);
const payloadWithoutAliasAndPK = pick(payloadWithA2O, without(fields, primaryKeyField, ...aliases));
const payloadWithTypeCasting = await payloadService.processValues('update', payloadWithoutAliasAndPK);
if (Object.keys(payloadWithTypeCasting).length > 0) {
try {
await trx(this.collection).update(payloadWithTypeCasting).whereIn(primaryKeyField, keys);
} catch (err: any) {
throw await translateDatabaseError(err);
}
}
const childrenRevisions = [...revisionsM2O, ...revisionsA2O];
nestedActionEvents.push(...nestedActionEventsM2O);
nestedActionEvents.push(...nestedActionEventsA2O);
for (const key of keys) {
const { revisions, nestedActionEvents: nestedActionEventsO2M } = await payloadService.processO2M(
payload,
key,
opts
);
childrenRevisions.push(...revisions);
nestedActionEvents.push(...nestedActionEventsO2M);
}
// If this is an authenticated action, and accountability tracking is enabled, save activity row
if (this.accountability && this.schema.collections[this.collection].accountability !== null) {
const activityService = new ActivityService({
knex: trx,
schema: this.schema,
});
const activity = await activityService.createMany(
keys.map((key) => ({
action: Action.UPDATE,
user: this.accountability!.user,
collection: this.collection,
ip: this.accountability!.ip,
user_agent: this.accountability!.userAgent,
origin: this.accountability!.origin,
item: key,
}))
);
if (this.schema.collections[this.collection].accountability === 'all') {
const itemsService = new ItemsService(this.collection, {
knex: trx,
schema: this.schema,
});
const snapshots = await itemsService.readMany(keys);
const revisionsService = new RevisionsService({
knex: trx,
schema: this.schema,
});
const revisions = (
await Promise.all(
activity.map(async (activity, index) => ({
activity: activity,
collection: this.collection,
item: keys[index],
data:
snapshots && Array.isArray(snapshots) ? JSON.stringify(snapshots[index]) : JSON.stringify(snapshots),
delta: await payloadService.prepareDelta(payloadWithTypeCasting),
}))
)
).filter((revision) => revision.delta);
const revisionIDs = await revisionsService.createMany(revisions);
for (let i = 0; i < revisionIDs.length; i++) {
const revisionID = revisionIDs[i];
if (opts?.onRevisionCreate) {
opts.onRevisionCreate(revisionID);
}
if (i === 0) {
// In case of a nested relational creation/update in a updateMany, the nested m2o/a2o
// creation is only done once. We treat the first updated item as the "main" update,
// with all other revisions on the current level as regular "flat" updates, and
// nested revisions as children of this first "root" item.
if (childrenRevisions.length > 0) {
await revisionsService.updateMany(childrenRevisions, { parent: revisionID });
}
}
}
}
}
});
if (this.cache && env.CACHE_AUTO_PURGE && opts?.autoPurgeCache !== false) {
await this.cache.clear();
}
if (opts?.emitEvents !== false) {
const actionEvent = {
event:
this.eventScope === 'items'
? ['items.update', `${this.collection}.items.update`]
: `${this.eventScope}.update`,
meta: {
payload,
keys,
collection: this.collection,
},
context: {
database: getDatabase(),
schema: this.schema,
accountability: this.accountability,
},
};
if (!opts?.bypassEmitAction) {
emitter.emitAction(actionEvent.event, actionEvent.meta, actionEvent.context);
} else {
opts.bypassEmitAction(actionEvent);
}
for (const nestedActionEvent of nestedActionEvents) {
emitter.emitAction(nestedActionEvent.event, nestedActionEvent.meta, nestedActionEvent.context);
}
}
return keys;
}
/**
* Upsert a single item
*/
async upsertOne(payload: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey> {
const primaryKeyField = this.schema.collections[this.collection].primary;
const primaryKey: PrimaryKey | undefined = payload[primaryKeyField];
if (primaryKey) {
validateKeys(this.schema, this.collection, primaryKeyField, primaryKey);
}
const exists =
primaryKey &&
!!(await this.knex
.select(primaryKeyField)
.from(this.collection)
.where({ [primaryKeyField]: primaryKey })
.first());
if (exists) {
return await this.updateOne(primaryKey as PrimaryKey, payload, opts);
} else {
return await this.createOne(payload, opts);
}
}
/**
* Upsert many items
*/
async upsertMany(payloads: Partial<Item>[], opts?: MutationOptions): Promise<PrimaryKey[]> {
const primaryKeys = await this.knex.transaction(async (trx) => {
const service = new ItemsService(this.collection, {
accountability: this.accountability,
schema: this.schema,
knex: trx,
});
const primaryKeys: PrimaryKey[] = [];
for (const payload of payloads) {
const primaryKey = await service.upsertOne(payload, { ...(opts || {}), autoPurgeCache: false });
primaryKeys.push(primaryKey);
}
return primaryKeys;
});
if (this.cache && env.CACHE_AUTO_PURGE && opts?.autoPurgeCache !== false) {
await this.cache.clear();
}
return primaryKeys;
}
/**
* Delete multiple items by query
*/
async deleteByQuery(query: Query, opts?: MutationOptions): Promise<PrimaryKey[]> {
const keys = await this.getKeysByQuery(query);
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, keys);
return keys.length ? await this.deleteMany(keys, opts) : [];
}
/**
* Delete a single item by primary key
*/
async deleteOne(key: PrimaryKey, opts?: MutationOptions): Promise<PrimaryKey> {
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, key);
await this.deleteMany([key], opts);
return key;
}
/**
* Delete multiple items by primary key
*/
async deleteMany(keys: PrimaryKey[], opts?: MutationOptions): Promise<PrimaryKey[]> {
const primaryKeyField = this.schema.collections[this.collection].primary;
validateKeys(this.schema, this.collection, primaryKeyField, keys);
if (this.accountability && this.accountability.admin !== true) {
const authorizationService = new AuthorizationService({
accountability: this.accountability,
schema: this.schema,
knex: this.knex,
});
await authorizationService.checkAccess('delete', this.collection, keys);
}
if (opts?.emitEvents !== false) {
await emitter.emitFilter(
this.eventScope === 'items' ? ['items.delete', `${this.collection}.items.delete`] : `${this.eventScope}.delete`,
keys,
{
collection: this.collection,
},
{
database: this.knex,
schema: this.schema,
accountability: this.accountability,
}
);
}
await this.knex.transaction(async (trx) => {
await trx(this.collection).whereIn(primaryKeyField, keys).delete();
if (this.accountability && this.schema.collections[this.collection].accountability !== null) {
const activityService = new ActivityService({
knex: trx,
schema: this.schema,
});
await activityService.createMany(
keys.map((key) => ({
action: Action.DELETE,
user: this.accountability!.user,
collection: this.collection,
ip: this.accountability!.ip,
user_agent: this.accountability!.userAgent,
origin: this.accountability!.origin,
item: key,
}))
);
}
});
if (this.cache && env.CACHE_AUTO_PURGE && opts?.autoPurgeCache !== false) {
await this.cache.clear();
}
if (opts?.emitEvents !== false) {
const actionEvent = {
event:
this.eventScope === 'items'
? ['items.delete', `${this.collection}.items.delete`]
: `${this.eventScope}.delete`,
meta: {
payload: keys,
keys: keys,
collection: this.collection,
},
context: {
database: getDatabase(),
schema: this.schema,
accountability: this.accountability,
},
};
if (!opts?.bypassEmitAction) {
emitter.emitAction(actionEvent.event, actionEvent.meta, actionEvent.context);
} else {
opts.bypassEmitAction(actionEvent);
}
}
return keys;
}
/**
* Read/treat collection as singleton
*/
async readSingleton(query: Query, opts?: QueryOptions): Promise<Partial<Item>> {
query = clone(query);
query.limit = 1;
const records = await this.readByQuery(query, opts);
const record = records[0];
if (!record) {
let fields = Object.entries(this.schema.collections[this.collection].fields);
const defaults: Record<string, any> = {};
if (query.fields && query.fields.includes('*') === false) {
fields = fields.filter(([name]) => {
return query.fields!.includes(name);
});
}
for (const [name, field] of fields) {
if (this.schema.collections[this.collection].primary === name) {
defaults[name] = null;
continue;
}
if (field.defaultValue) defaults[name] = field.defaultValue;
}
return defaults as Partial<Item>;
}
return record;
}
/**
* Upsert/treat collection as singleton
*/
async upsertSingleton(data: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey> {
const primaryKeyField = this.schema.collections[this.collection].primary;
const record = await this.knex.select(primaryKeyField).from(this.collection).limit(1).first();
if (record) {
return await this.updateOne(record[primaryKeyField], data, opts);
}
return await this.createOne(data, opts);
}
}