59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
module.exports = Self => {
|
|
/**
|
|
* Catches database errors overriding
|
|
* model.create() and model.upsert() methods
|
|
* @param {Object} replaceErrFunc - Callback
|
|
*/
|
|
Self.rewriteDbError = function(replaceErrFunc) {
|
|
this.once('attached', () => {
|
|
let realUpsert = this.upsert;
|
|
this.upsert = async(data, options, cb) => {
|
|
if (options instanceof Function) {
|
|
cb = options;
|
|
options = null;
|
|
}
|
|
|
|
try {
|
|
await realUpsert.call(this, data, options);
|
|
if (cb) cb();
|
|
} catch (err) {
|
|
let myErr = replaceErr(err, replaceErrFunc);
|
|
if (cb)
|
|
cb(myErr);
|
|
else
|
|
throw myErr;
|
|
}
|
|
};
|
|
|
|
let realCreate = this.create;
|
|
this.create = async(data, options, cb) => {
|
|
if (options instanceof Function) {
|
|
cb = options;
|
|
options = null;
|
|
}
|
|
|
|
try {
|
|
await realCreate.call(this, data, options);
|
|
if (cb) cb();
|
|
} catch (err) {
|
|
let myErr = replaceErr(err, replaceErrFunc);
|
|
if (cb)
|
|
cb(myErr);
|
|
else
|
|
throw myErr;
|
|
}
|
|
};
|
|
});
|
|
};
|
|
|
|
function replaceErr(err, replaceErrFunc) {
|
|
if (Array.isArray(err)) {
|
|
let errs = [];
|
|
for (let e of err)
|
|
errs.push(replaceErrFunc(e));
|
|
return errs;
|
|
}
|
|
return replaceErrFunc(err);
|
|
}
|
|
};
|