Improving consistency of model saving, making sure that any validation which could fail happens before any updates are carried out.

This commit is contained in:
mike12345567 2020-10-12 16:51:41 +01:00
parent 8df3a3f8de
commit 352ff82885
2 changed files with 11 additions and 8 deletions

View File

@ -33,6 +33,7 @@ exports.save = async function(ctx) {
views: {}, views: {},
...rest, ...rest,
} }
let renameDocs = []
// if the model obj had an _id then it will have been retrieved // if the model obj had an _id then it will have been retrieved
const oldModel = ctx.preExisting const oldModel = ctx.preExisting
@ -49,14 +50,11 @@ exports.save = async function(ctx) {
include_docs: true, include_docs: true,
}) })
) )
renameDocs = records.rows.map(({ doc }) => {
const docs = records.rows.map(({ doc }) => {
doc[_rename.updated] = doc[_rename.old] doc[_rename.updated] = doc[_rename.old]
delete doc[_rename.old] delete doc[_rename.old]
return doc return doc
}) })
await db.bulkDocs(docs)
delete modelToSave._rename delete modelToSave._rename
} }
@ -69,9 +67,6 @@ exports.save = async function(ctx) {
modelView.schema = modelToSave.schema modelView.schema = modelToSave.schema
} }
const result = await db.post(modelToSave)
modelToSave._rev = result.rev
// update linked records // update linked records
await linkRecords.updateLinks({ await linkRecords.updateLinks({
instanceId, instanceId,
@ -82,6 +77,14 @@ exports.save = async function(ctx) {
oldModel: oldModel, oldModel: oldModel,
}) })
// don't perform any updates until relationships have been
// checked by the updateLinks function
if (renameDocs.length !== 0) {
await db.bulkDocs(renameDocs)
}
const result = await db.post(modelToSave)
modelToSave._rev = result.rev
ctx.eventEmitter && ctx.eventEmitter &&
ctx.eventEmitter.emitModel(`model:save`, instanceId, modelToSave) ctx.eventEmitter.emitModel(`model:save`, instanceId, modelToSave)

View File

@ -161,7 +161,7 @@ class LinkController {
}) })
// now add the docs to be deleted to the bulk operation // now add the docs to be deleted to the bulk operation
operations.push(...toDeleteDocs) operations.push(...toDeleteDocs)
// replace this field with a simple entry to denote there are links // remove the field from this row, link doc will be added to record on way out
delete record[fieldName] delete record[fieldName]
} }
} }