From 9bf568ecb13d50ae75455f3566963203477c1396 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Mon, 12 Oct 2020 16:37:08 +0100 Subject: [PATCH] Fixes for deleting records when a table is deleted. --- packages/server/src/api/controllers/model.js | 8 ++++---- packages/server/src/db/utils.js | 21 ++++++++++++-------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/packages/server/src/api/controllers/model.js b/packages/server/src/api/controllers/model.js index 87a2449f76..74e3494eba 100644 --- a/packages/server/src/api/controllers/model.js +++ b/packages/server/src/api/controllers/model.js @@ -105,11 +105,8 @@ exports.save = async function(ctx) { exports.destroy = async function(ctx) { const instanceId = ctx.user.instanceId const db = new CouchDB(instanceId) - const modelToDelete = await db.get(ctx.params.modelId) - await db.remove(modelToDelete) - // Delete all records for that model const records = await db.allDocs( getRecordParams(ctx.params.modelId, null, { @@ -117,7 +114,7 @@ exports.destroy = async function(ctx) { }) ) await db.bulkDocs( - records.rows.map(record => ({ _id: record.id, _deleted: true })) + records.rows.map(record => ({ ...record.doc, _deleted: true })) ) // update linked records @@ -127,6 +124,9 @@ exports.destroy = async function(ctx) { model: modelToDelete, }) + // don't remove the table itself until very end + await db.remove(modelToDelete) + ctx.eventEmitter && ctx.eventEmitter.emitModel(`model:delete`, instanceId, modelToDelete) ctx.status = 200 diff --git a/packages/server/src/db/utils.js b/packages/server/src/db/utils.js index a167966a4e..56572e1170 100644 --- a/packages/server/src/db/utils.js +++ b/packages/server/src/db/utils.js @@ -57,21 +57,26 @@ exports.generateModelID = () => { /** * Gets the DB allDocs/query params for retrieving a record. - * @param {string} modelId The model in which the records have been stored. + * @param {string|null} modelId The model in which the records have been stored. * @param {string|null} recordId The ID of the record which is being specifically queried for. This can be * left null to get all the records in the model. * @param {object} otherProps Any other properties to add to the request. * @returns {object} Parameters which can then be used with an allDocs request. */ -exports.getRecordParams = (modelId, recordId = null, otherProps = {}) => { +exports.getRecordParams = ( + modelId = null, + recordId = null, + otherProps = {} +) => { if (modelId == null) { - throw "Cannot build params for records without a model ID" + return getDocParams(DocumentTypes.RECORD, null, otherProps) + } else { + const endOfKey = + recordId == null + ? `${modelId}${SEPARATOR}` + : `${modelId}${SEPARATOR}${recordId}` + return getDocParams(DocumentTypes.RECORD, endOfKey, otherProps) } - const endOfKey = - recordId == null - ? `${modelId}${SEPARATOR}` - : `${modelId}${SEPARATOR}${recordId}` - return getDocParams(DocumentTypes.RECORD, endOfKey, otherProps) } /**