MCPcopy
hub / github.com/directus/directus / upsertOne

Method upsertOne

api/src/services/items.ts:1021–1043  ·  view source on GitHub ↗

* Upsert a single item. * * Uses `this.createOne` / `this.updateOne` under the hood.

(payload: Partial<Item>, opts?: MutationOptions)

Source from the content-addressed store, hash-verified

1019 * Uses `this.createOne` / `this.updateOne` under the hood.
1020 */
1021 async upsertOne(payload: Partial<Item>, opts?: MutationOptions): Promise<PrimaryKey> {
1022 const primaryKeyField = this.schema.collections[this.collection]!.primary;
1023 const primaryKey: PrimaryKey | undefined = payload[primaryKeyField];
1024
1025 if (primaryKey) {
1026 validateKeys(this.schema, this.collection, primaryKeyField, primaryKey);
1027 }
1028
1029 const exists =
1030 primaryKey &&
1031 !!(await this.knex
1032 .select(primaryKeyField)
1033 .from(this.collection)
1034 .where({ [primaryKeyField]: primaryKey })
1035 .first());
1036
1037 if (exists) {
1038 const { [primaryKeyField]: _, ...data } = payload;
1039 return await this.updateOne(primaryKey as PrimaryKey, data as Partial<Item>, opts);
1040 } else {
1041 return await this.createOne(payload, opts);
1042 }
1043 }
1044
1045 /**
1046 * Upsert many items.

Callers

nothing calls this directly

Calls 4

updateOneMethod · 0.95
createOneMethod · 0.95
validateKeysFunction · 0.85
fromMethod · 0.80

Tested by

no test coverage detected