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:
parent
8df3a3f8de
commit
352ff82885
|
@ -33,6 +33,7 @@ exports.save = async function(ctx) {
|
|||
views: {},
|
||||
...rest,
|
||||
}
|
||||
let renameDocs = []
|
||||
|
||||
// if the model obj had an _id then it will have been retrieved
|
||||
const oldModel = ctx.preExisting
|
||||
|
@ -49,14 +50,11 @@ exports.save = async function(ctx) {
|
|||
include_docs: true,
|
||||
})
|
||||
)
|
||||
|
||||
const docs = records.rows.map(({ doc }) => {
|
||||
renameDocs = records.rows.map(({ doc }) => {
|
||||
doc[_rename.updated] = doc[_rename.old]
|
||||
delete doc[_rename.old]
|
||||
return doc
|
||||
})
|
||||
|
||||
await db.bulkDocs(docs)
|
||||
delete modelToSave._rename
|
||||
}
|
||||
|
||||
|
@ -69,9 +67,6 @@ exports.save = async function(ctx) {
|
|||
modelView.schema = modelToSave.schema
|
||||
}
|
||||
|
||||
const result = await db.post(modelToSave)
|
||||
modelToSave._rev = result.rev
|
||||
|
||||
// update linked records
|
||||
await linkRecords.updateLinks({
|
||||
instanceId,
|
||||
|
@ -82,6 +77,14 @@ exports.save = async function(ctx) {
|
|||
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.emitModel(`model:save`, instanceId, modelToSave)
|
||||
|
||||
|
|
|
@ -161,7 +161,7 @@ class LinkController {
|
|||
})
|
||||
// now add the docs to be deleted to the bulk operation
|
||||
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]
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue