* Upsert a single item. * * Uses `this.createOne` / `this.updateOne` under the hood.
(payload: Partial<Item>, opts?: MutationOptions)
| 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. |
nothing calls this directly
no test coverage detected