From abac6ad83ad71f40047473c81d50b6af80ad41b2 Mon Sep 17 00:00:00 2001 From: Tim Leslie Date: Fri, 20 Mar 2020 10:51:25 +1100 Subject: [PATCH] Knex adapter internal updates (#2492) --- .changeset/fast-windows-kneel.md | 5 ++++ packages/adapter-knex/lib/adapter-knex.js | 35 +++++++++++++++-------- 2 files changed, 28 insertions(+), 12 deletions(-) create mode 100644 .changeset/fast-windows-kneel.md diff --git a/.changeset/fast-windows-kneel.md b/.changeset/fast-windows-kneel.md new file mode 100644 index 00000000000..e320f31c1f4 --- /dev/null +++ b/.changeset/fast-windows-kneel.md @@ -0,0 +1,5 @@ +--- +'@keystonejs/adapter-knex': patch +--- + +Refactored internals to prepare for future changes. diff --git a/packages/adapter-knex/lib/adapter-knex.js b/packages/adapter-knex/lib/adapter-knex.js index b33af9d3081..5ddbf6a37b5 100644 --- a/packages/adapter-knex/lib/adapter-knex.js +++ b/packages/adapter-knex/lib/adapter-knex.js @@ -286,6 +286,8 @@ class KnexListAdapter extends BaseListAdapter { }); } + ////////// Mutations ////////// + async _processNonRealFields(data, processFunction) { return resolveAllKeys( arrayToObject( @@ -300,7 +302,22 @@ class KnexListAdapter extends BaseListAdapter { ); } - ////////// Mutations ////////// + async _createSingle(realData) { + const item = ( + await this._query() + .insert(realData) + .into(this.tableName) + .returning('*') + )[0]; + return { item, itemId: item.id }; + } + + async _setNullByValue({ tableName, columnName, value }) { + return this._query() + .table(tableName) + .where(columnName, value) + .update({ [columnName]: null }); + } async _createOrUpdateField({ value, adapter, itemId }) { const rel = { @@ -334,16 +351,11 @@ class KnexListAdapter extends BaseListAdapter { const realData = pick(data, this.realKeys); // Insert the real data into the table - const item = ( - await this._query() - .insert(realData) - .into(this.tableName) - .returning('*') - )[0]; + const { item, itemId } = await this._createSingle(realData); // For every many-field, update the many-table const manyItem = await this._processNonRealFields(data, async ({ value, adapter }) => - this._createOrUpdateField({ value, adapter, itemId: item.id }) + this._createOrUpdateField({ value, adapter, itemId }) ); return { ...item, ...manyItem }; @@ -351,6 +363,7 @@ class KnexListAdapter extends BaseListAdapter { async _update(id, data) { const realData = pick(data, this.realKeys); + // Update the real data const query = this._query() .table(this.tableName) @@ -428,15 +441,13 @@ class KnexListAdapter extends BaseListAdapter { .where(columnNames[this.key].near, id) .del(); } else { - return this._query() - .table(tableName) - .where(columnName, id) - .update({ [columnName]: null }); + return this._setNullByValue({ tableName, columnName, value: id }); } }) ) ) ); + // Delete the actual item return this._query() .table(this.tableName)