@joktec/mongo
Version:
JokTec - Mongo Service
41 lines • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongoCatch = exports.MongoException = void 0;
const core_1 = require("@joktec/core");
const lodash_1 = require("lodash");
const mongoose_1 = require("mongoose");
class MongoException extends core_1.InternalServerException {
constructor(msg = 'MONGO_EXCEPTION', error) {
super(msg, error);
}
}
exports.MongoException = MongoException;
exports.MongoCatch = (0, core_1.BaseMethodDecorator)(async (options) => {
const { method, args } = options;
try {
return await method(...args);
}
catch (err) {
if (err instanceof core_1.Exception) {
throw err;
}
if (err instanceof mongoose_1.Error.ValidationError) {
const validationBuilder = core_1.ValidatorBuilder.init(MongoException.name);
Object.values(err.errors).map(errItem => {
const msg = errItem instanceof mongoose_1.Error.CastError ? `${errItem.path}_INVALID`.toUpperCase() : errItem.message;
validationBuilder.add(errItem.path, msg, errItem.value);
});
validationBuilder.throw();
}
if ((err?.code === 11000 || err?.code === 11001) && (0, lodash_1.has)(err, 'keyValue')) {
const validationBuilder = core_1.ValidatorBuilder.init(MongoException.name);
Object.entries(err['keyValue']).map(([path, value]) => {
const msg = `${(0, lodash_1.upperCase)(path)}_DUPLICATED_VALUE`;
validationBuilder.add(path, msg, value);
});
validationBuilder.throw();
}
throw new MongoException(err.message, err);
}
});
//# sourceMappingURL=mongo.exception.js.map