2018-09-18 08:11:51 +00:00
|
|
|
module.exports = Self => {
|
2018-10-15 09:43:57 +00:00
|
|
|
/**
|
|
|
|
* Catches database errors overriding
|
|
|
|
* model.create() and model.upsert() methods
|
|
|
|
* @param {Object} replaceErrFunc - Callback
|
|
|
|
*/
|
2018-09-18 08:11:51 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
};
|