Skip to content

Commit

Permalink
Knex adapter internal updates (#2492)
Browse files Browse the repository at this point in the history
  • Loading branch information
timleslie authored Mar 19, 2020
1 parent d65c7ba commit abac6ad
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/fast-windows-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystonejs/adapter-knex': patch
---

Refactored internals to prepare for future changes.
35 changes: 23 additions & 12 deletions packages/adapter-knex/lib/adapter-knex.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,8 @@ class KnexListAdapter extends BaseListAdapter {
});
}

////////// Mutations //////////

async _processNonRealFields(data, processFunction) {
return resolveAllKeys(
arrayToObject(
Expand All @@ -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 = {
Expand Down Expand Up @@ -334,23 +351,19 @@ 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 };
}

async _update(id, data) {
const realData = pick(data, this.realKeys);

// Update the real data
const query = this._query()
.table(this.tableName)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit abac6ad

Please sign in to comment.