Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
refactor: use async/await for subdoc post save
  • Loading branch information
vkarpov15 committed Jul 7, 2024
commit 50f1a7385a840b47c0b1bc5ad8b7764cd113d0f1
38 changes: 24 additions & 14 deletions lib/plugins/saveSubdocs.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,31 +58,41 @@ module.exports = function saveSubdocs(schema) {
await Promise.all(promises);
});

schema.s.hooks.post('save', function saveSubdocsPostSave(doc, next) {
schema.s.hooks.post('save', async function saveSubdocsPostSave() {
if (this.$isSubdocument) {
next();
return;
}

const _this = this;
const subdocs = this.$getAllSubdocs();

if (!subdocs.length) {
next();
return;
}

each(subdocs, function(subdoc, cb) {
subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) {
cb(err);
});
}, function(error) {
if (error) {
return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
next(error);
const promises = [];
for (const subdoc of subdocs) {
promises.push(new Promise((resolve, reject) => {
subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) {
if (err) {
return reject(err);
}
resolve();
});
}
next();
});
}));
}

try {
await Promise.all(promises);
} catch (error) {
await new Promise((resolve, reject) => {
this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
if (error) {
return reject(error);
}
resolve();
});
});
}
}, null, unshift);
};