@knovator/masters-node
Version:
NodeJS backend for @knovator/masters
1,653 lines (1,441 loc) • 58.1 kB
JavaScript
import express from 'express';
import joi from 'joi';
import { Schema, model } from 'mongoose';
import mongoosePaginate from 'mongoose-paginate-v2';
import uniqueValidator from 'mongoose-unique-validator';
var VALIDATION = {
MASTER_EXISTS: 'Record with same code is already exists'
};
var RESPONSE_CODE = {
DEFAULT: "SUCCESS",
ERROR: "ERROR"
};
var success = 200;
var create$1 = 201;
var internalServerError = 500;
var validationError = 422;
var defaults = {
logger: console,
catchAsync: function catchAsync(fn) {
return function (req, res, next) {
Promise.resolve(fn(req, res, next))["catch"](function (err) {
// this.logger.error(err.message);
res.status(internalServerError).json({
code: RESPONSE_CODE.ERROR,
message: err.message,
data: {}
});
});
};
},
authentication: function authentication(_req, _res, next) {
return next();
},
preDelete: function preDelete(_record) {
return Promise.resolve({});
},
postUpdate: function postUpdate(_record) {
return Promise.resolve({});
},
languages: []
};
function _regeneratorRuntime() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
_regeneratorRuntime = function () {
return exports;
};
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function (obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return generator._invoke = function (innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}(innerFn, self, context), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
this._invoke = function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
};
}
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (context.delegate = null, "throw" === context.method) {
if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (object) {
var keys = [];
for (var key in object) keys.push(key);
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function (skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function () {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function (exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function (type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function (record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
catch: function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _extends() {
_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
var failureResponse = function failureResponse(data, res) {
var i = 0;
if ((data == null ? void 0 : data.name) === "ValidationError") {
Object.keys(data == null ? void 0 : data.errors).forEach(function (key) {
if (i !== 1) {
data.message = data.errors[key].message;
}
i++;
});
}
res.message = data.message;
return res.status(validationError).json({
code: RESPONSE_CODE.ERROR,
message: data.message ? data.message : data
});
};
var successResponse = function successResponse(data, res) {
return res.status(success).json({
code: RESPONSE_CODE.DEFAULT,
message: res.message,
data: data
});
};
var createdDocumentResponse = function createdDocumentResponse(data, res) {
return res.status(create$1).json({
code: RESPONSE_CODE.DEFAULT,
message: res.message,
data: data
});
};
var recordNotFound = function recordNotFound(res) {
return res.status(success).json({
code: RESPONSE_CODE.DEFAULT,
message: res.message,
data: {}
});
};
var inValidParam = function inValidParam(message, res) {
message = message.replace(/\"/g, '');
res.message = message;
return res.status(validationError).json({
code: RESPONSE_CODE.ERROR,
message: message,
data: {}
});
};
var validate = function validate(validator) {
return /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res, next) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return validator.validateAsync(req.body);
case 3:
req.body = _context.sent;
next();
_context.next = 13;
break;
case 7:
_context.prev = 7;
_context.t0 = _context["catch"](0);
defaults.logger.error("ValidationError", _context.t0);
if (!_context.t0.isJoi) {
_context.next = 12;
break;
}
return _context.abrupt("return", inValidParam(_context.t0.message, res));
case 12:
next(failureResponse(_context.t0.message, res));
case 13:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 7]]);
}));
return function (_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
};
var myCustomLabels = {
totalDocs: 'itemCount',
docs: 'data',
limit: 'perPage',
page: 'currentPage',
nextPage: 'next',
prevPage: 'prev',
totalPages: 'pageCount',
pagingCounter: 'slNo',
meta: 'paginator'
};
mongoosePaginate.paginate.options = {
customLabels: myCustomLabels
};
var namesSchema = /*#__PURE__*/defaults.languages.reduce(function (acc, lang) {
acc[lang.code] = {
type: String,
required: true
};
return acc;
}, {});
var MasterSchema = /*#__PURE__*/new Schema({
name: {
type: String
},
// @ts-ignore
names: namesSchema,
code: {
type: String,
required: true
},
desc: {
type: String
},
parentId: {
type: Schema.Types.ObjectId,
ref: 'master'
},
parentCode: {
type: String
},
img: {
type: Schema.Types.ObjectId,
ref: 'file'
},
isDefault: {
type: Boolean,
"default": false
},
isActive: {
type: Boolean,
"default": true
},
seq: {
type: Number
},
webDsply: {
type: String
},
isWebVisible: {
type: Boolean
},
canDel: {
type: Boolean,
"default": true
},
canEdit: {
type: Boolean,
"default": true
},
deletedAt: {
type: Date
},
extra: {
type: String
},
createdBy: {
type: Schema.Types.ObjectId,
ref: 'user'
},
updatedBy: [{
type: Schema.Types.ObjectId,
ref: 'user'
}],
deletedBy: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}, {
timestamps: {
createdAt: 'createdAt',
updatedAt: 'updatedAt'
}
});
MasterSchema.pre('save', /*#__PURE__*/function () {
var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(next) {
var masterData, number;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!this.parentId) {
_context.next = 6;
break;
}
_context.next = 3;
return Master.findOne({
parentId: this.parentId,
deletedAt: {
$exists: false
}
}).sort({
createdAt: -1
});
case 3:
masterData = _context.sent;
number = masterData && masterData.seq ? masterData.seq + 1 : 1;
if (!this.seq) {
this.seq = number;
}
case 6:
next();
case 7:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}());
MasterSchema.pre('findOne', function (next) {
this.getQuery().deletedAt = {
$exists: false
};
next();
});
MasterSchema.pre('find', function (next) {
this.getQuery().deletedAt = {
$exists: false
};
next();
});
MasterSchema.pre('deleteOne', {
document: true,
query: false
}, /*#__PURE__*/function () {
var _ref2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(next) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(typeof defaults.preDelete === 'function')) {
_context2.next = 3;
break;
}
_context2.next = 3;
return defaults.preDelete(this);
case 3:
next();
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
return function (_x2) {
return _ref2.apply(this, arguments);
};
}());
MasterSchema.post('findOneAndUpdate', /*#__PURE__*/function () {
var _ref3 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(doc, next) {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(typeof defaults.postUpdate === 'function')) {
_context3.next = 3;
break;
}
_context3.next = 3;
return defaults.postUpdate(doc);
case 3:
next();
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x3, _x4) {
return _ref3.apply(this, arguments);
};
}());
MasterSchema.method('toJSON', function () {
var obj = this.toObject();
delete obj['__v'];
return obj;
});
MasterSchema.plugin(uniqueValidator);
MasterSchema.plugin(mongoosePaginate);
var Master = /*#__PURE__*/model('master', MasterSchema, 'master');
function bulkUpdate(_x, _x2, _x3) {
return _bulkUpdate.apply(this, arguments);
}
function _bulkUpdate() {
_bulkUpdate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(Modal, filter, data) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return Modal.updateMany(filter, data);
case 3:
return _context.abrupt("return", _context.sent);
case 6:
_context.prev = 6;
_context.t0 = _context["catch"](0);
throw new Error(_context.t0.message);
case 9:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 6]]);
}));
return _bulkUpdate.apply(this, arguments);
}
function findOneAndUpdateDocument(_x4, _x5, _x6, _x7, _x8) {
return _findOneAndUpdateDocument.apply(this, arguments);
}
function _findOneAndUpdateDocument() {
_findOneAndUpdateDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(Modal, filter, data, options, populate) {
var response;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (options === void 0) {
options = {
"new": true
};
}
_context2.prev = 1;
_context2.next = 4;
return Modal.findOneAndUpdate(filter, data, options).populate(populate || []);
case 4:
response = _context2.sent;
return _context2.abrupt("return", response);
case 8:
_context2.prev = 8;
_context2.t0 = _context2["catch"](1);
throw new Error(_context2.t0.message);
case 11:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[1, 8]]);
}));
return _findOneAndUpdateDocument.apply(this, arguments);
}
function createDocument(_x9, _x10) {
return _createDocument.apply(this, arguments);
}
function _createDocument() {
_createDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(Modal, data) {
var response;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_context3.next = 3;
return Modal.create(data);
case 3:
response = _context3.sent;
return _context3.abrupt("return", response);
case 7:
_context3.prev = 7;
_context3.t0 = _context3["catch"](0);
throw new Error(_context3.t0.message);
case 10:
case "end":
return _context3.stop();
}
}
}, _callee3, null, [[0, 7]]);
}));
return _createDocument.apply(this, arguments);
}
function getDocumentByQuery(_x11, _x12, _x13) {
return _getDocumentByQuery.apply(this, arguments);
}
function _getDocumentByQuery() {
_getDocumentByQuery = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(Modal, where, select) {
var response;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (select === void 0) {
select = [];
}
_context4.prev = 1;
_context4.next = 4;
return Modal.findOne(where, select);
case 4:
response = _context4.sent;
return _context4.abrupt("return", response);
case 8:
_context4.prev = 8;
_context4.t0 = _context4["catch"](1);
throw new Error(_context4.t0.message);
case 11:
case "end":
return _context4.stop();
}
}
}, _callee4, null, [[1, 8]]);
}));
return _getDocumentByQuery.apply(this, arguments);
}
function countDocument(_x14, _x15) {
return _countDocument.apply(this, arguments);
}
function _countDocument() {
_countDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(Modal, where) {
var count;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
_context5.next = 3;
return Modal.where(where).countDocuments();
case 3:
count = _context5.sent;
return _context5.abrupt("return", count);
case 7:
_context5.prev = 7;
_context5.t0 = _context5["catch"](0);
throw new Error(_context5.t0.message);
case 10:
case "end":
return _context5.stop();
}
}
}, _callee5, null, [[0, 7]]);
}));
return _countDocument.apply(this, arguments);
}
function getAllDocuments(_x16, _x17, _x18) {
return _getAllDocuments.apply(this, arguments);
}
function _getAllDocuments() {
_getAllDocuments = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(Modal, where, options) {
var documents;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.prev = 0;
// @ts-ignore
documents = Modal.paginate(where, options);
return _context6.abrupt("return", documents);
case 5:
_context6.prev = 5;
_context6.t0 = _context6["catch"](0);
throw new Error(_context6.t0.message);
case 8:
case "end":
return _context6.stop();
}
}
}, _callee6, null, [[0, 5]]);
}));
return _getAllDocuments.apply(this, arguments);
}
var create = /*#__PURE__*/joi.object({
name: joi.string().optional(),
code: joi.string().uppercase().replace(/\s+/g, '_') // .external(method)
.required(),
names: joi.object().optional(),
extra: joi.string().optional(),
desc: joi.string().allow('').optional(),
parentId: joi.string().optional(),
parentCode: joi.string().optional(),
img: joi.string().optional(),
seq: joi.number().optional(),
isDefault: joi["boolean"]().optional(),
webDsply: joi.string().allow('').optional(),
isWebVisible: joi["boolean"]().optional(),
canDel: joi["boolean"]()["default"](true),
canEdit: joi["boolean"]()["default"](true),
createdBy: joi.object().optional(),
updatedBy: joi.object().optional(),
deletedBy: joi.object().optional(),
deletedAt: joi.date().optional(),
isActive: joi["boolean"]()["default"](true)
}).custom( /*#__PURE__*/function () {
var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(obj) {
var parentId, code, search, result;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
parentId = obj.parentId, code = obj.code;
search = {
code: code
};
if (parentId) search.parentId = parentId;
_context.next = 5;
return getDocumentByQuery(Master, search);
case 5:
result = _context.sent;
if (!result) {
_context.next = 8;
break;
}
throw new Error(VALIDATION.MASTER_EXISTS);
case 8:
return _context.abrupt("return", obj);
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}()).unknown(false);
var update = /*#__PURE__*/joi.object({
name: joi.string().optional(),
desc: joi.optional(),
names: joi.object().optional(),
img: joi.string().optional().allow(null).allow(''),
webDsply: joi.string().allow('').optional(),
isWebVisible: joi["boolean"]().optional(),
canDel: joi["boolean"]().optional(),
canEdit: joi["boolean"]().optional(),
isActive: joi["boolean"]().optional(),
isDefault: joi["boolean"]().optional(),
seq: joi.number().optional(),
updatedBy: joi.object().optional(),
extra: joi.string().optional()
}).unknown(false);
var activate = /*#__PURE__*/joi.object({
updatedBy: joi.object().optional(),
isActive: joi["boolean"]().optional()
}).unknown(false);
var isDefault = /*#__PURE__*/joi.object({
updatedBy: joi.object().optional(),
isDefault: joi["boolean"]().optional()
}).unknown(false);
var webVisible = /*#__PURE__*/joi.object({
updatedBy: joi.object().optional(),
isWebVisible: joi["boolean"]().optional()
}).unknown(false);
var sequence = /*#__PURE__*/joi.object({
updatedBy: joi.object().optional(),
sequences: joi.array().required()
}).unknown(false);
var list = /*#__PURE__*/joi.object({
language: joi.string().optional(),
search: joi.string().allow('')["default"](''),
query: joi.object({
parentId: joi.string().optional(),
parentCode: joi.optional(),
_id: joi.string().optional(),
extra: joi.string().optional(),
code: joi.string().optional()
})["default"]({}),
options: joi.object({
sort: joi.alternatives()["try"](joi.object(), joi.string()).optional(),
populate: joi.array().items().optional(),
offset: joi.number().optional(),
page: joi.number().optional(),
limit: joi.number().optional(),
pagination: joi["boolean"]()["default"](false)
})["default"]({}),
isCountOnly: joi["boolean"]()["default"](false),
isActive: joi["boolean"]().optional(),
all: joi["boolean"]().optional(),
createdBy: joi.object().optional()
}).unknown(false);
var _delete = /*#__PURE__*/joi.object({
id: joi.string().required(),
updatedBy: joi.object().optional(),
deletedBy: joi.object().optional(),
deletedAt: joi.date().optional()
}).unknown(false);
var defaultMaster$1 = /*#__PURE__*/function () {
var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(id, data) {
var masterData, result;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return getDocumentByQuery(Master, {
_id: id
});
case 3:
masterData = _context.sent;
if (!masterData.parentId) {
_context.next = 7;
break;
}
_context.next = 7;
return bulkUpdate(Master, {
parentId: masterData.parentId,
isDefault: true
}, {
isDefault: false
});
case 7:
_context.next = 9;
return findOneAndUpdateDocument(Master, {
_id: id
}, data, {
"new": true
}, {
path: 'img',
select: 'uri'
});
case 9:
result = _context.sent;
return _context.abrupt("return", result);
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](0);
throw new Error(_context.t0.message);
case 16:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 13]]);
}));
return function defaultMaster(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
var sequenceMaster$1 = /*#__PURE__*/function () {
var _ref2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(data) {
var bulkSequenceUpdates, result;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
bulkSequenceUpdates = data.map(function (obj) {
return {
updateOne: {
filter: {
_id: obj.id
},
// If you were using the MongoDB driver directly, you'd need to do
// `update: { $set: { field: ... } }` but mongoose adds $set for you
update: {
seq: obj.seq
}
}
};
});
_context2.next = 4;
return Master.bulkWrite(bulkSequenceUpdates);
case 4:
result = _context2.sent;
return _context2.abrupt("return", result);
case 8:
_context2.prev = 8;
_context2.t0 = _context2["catch"](0);
throw new Error(_context2.t0.message);
case 11:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[0, 8]]);
}));
return function sequenceMaster(_x3) {
return _ref2.apply(this, arguments);
};
}();
var listMaster$1 = /*#__PURE__*/function () {
var _ref3 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(customOptions, isCountOnly, search, customQuery, onlyActive, populate, pagination, languages) {
var query, options, result;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (onlyActive === void 0) {
onlyActive = [true];
}
if (pagination === void 0) {
pagination = true;
}
if (languages === void 0) {
languages = undefined;
}
_context3.prev = 3;
query = _extends({
deletedAt: {
$exists: false
},
isActive: {
$in: onlyActive
}
}, search && Array.isArray(languages) && languages.length > 0 ? {
$and: languages.map(function (langKey) {
var _ref4;
return _ref4 = {}, _ref4["names." + langKey] = {
$regex: search,
$options: 'i'
}, _ref4;
})
} : search ? {
name: {
$regex: search,
$options: 'i'
}
} : {}, {
$or: [{
code: {
$regex: search.replace(/\s+/g, '_'),
$options: 'i'
}
}].concat(typeof customQuery.extra !== 'undefined' ? [{
extra: {
$regex: customQuery.extra,
$options: 'i'
}
}] : [], typeof customQuery.code !== 'undefined' ? [{
code: {
$regex: customQuery.code,
$options: 'i'
}
}] : [])
}, customQuery.extra ? {
extra: {
$regex: customQuery.extra,
$options: 'i'
}
} : {}, customQuery.code ? {
code: {
$regex: customQuery.code,
$options: 'i'
}
} : {});
options = {
select: [],
collation: '',
customLabels: {},
useEstimatedCount: true,
useCustomCountFn: true,
forceCountFn: true,
read: {},
options: {},
projection: '',
// lean: true,
// leanWithId: true,
populate: Array.isArray(populate) ? populate : ['img'],
pagination: pagination
};
if (customQuery.parentCode) {
if (Array.isArray(customQuery.parentCode)) {
Object.assign(query, {
parentCode: {
$in: customQuery.parentCode
}
});
} else {
Object.assign(query, {
parentCode: customQuery.parentCode
});
}
} else {
Object.assign(query, {
parentCode: {
$exists: false
}
});
}
if (!isCountOnly) {
_context3.next = 15;
break;
}
_context3.next = 10;
return countDocument(Master, query);
case 10:
result = _context3.sent;
result = {
totalRecords: result
};
return _context3.abrupt("return", result);
case 15:
if (options !== undefined) {
options = _extends({}, options, customOptions);
} // @ts-ignore
_context3.next = 18;
return getAllDocuments(Master, query, options);
case 18:
result = _context3.sent;
if (result) {
_context3.next = 21;
break;
}
return _context3.abrupt("return", false);
case 21:
return _context3.abrupt("return", result);
case 22:
_context3.next = 27;
break;
case 24:
_context3.prev = 24;
_context3.t0 = _context3["catch"](3);
throw new Error(_context3.t0.message);
case 27:
case "end":
return _context3.stop();
}
}
}, _callee3, null, [[3, 24]]);
}));
return function listMaster(_x4, _x5, _x6, _x7, _x8, _x9, _x10, _x11) {
return _ref3.apply(this, arguments);
};
}();
var catchAsync = function catchAsync(fn) {
return defaults.catchAsync(fn);
};
var createMaster = /*#__PURE__*/catchAsync( /*#__PURE__*/function () {
var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, res) {
var data, masterData, result, _req$i18n, section;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
data = new Master(_extends({}, req.body));
if (!(data.parentId && data.isDefault)) {
_context.next = 4;
break;
}
_context.next = 4;
return bulkUpdate(Master, {
parentId: data.parentId,
isDefault: true
}, {
isDefault: false
});
case 4:
_context.next = 6;
return createDocument(Master, data);
case 6:
masterData = _context.sent;
_context.next = 9;
return Master.populate(masterData, [{
path: 'img',
select: 'uri'
}]);
case 9:
result = _context.sent;
if (!result) {
_context.next = 14;
break;
}
section = result.parentCode ? 'submaster' : 'master';
res.message = req == null ? void 0 : (_req$i18n = req.i18n) == null ? void 0 : _req$i18n.t(section + ".create");
return _context.abrupt("return", createdDocumentResponse(result, res));
case 14:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
}());
var updateMaster = /*#__PURE__*/catchAsync( /*#__PURE__*/function () {
var _ref2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, res) {
var id, data, masterData, result, _req$i18n2, section;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
id = req.params.id;
data = req.body;
if (!data.isDefault) {
_context2.next = 9;
break;
}
_context2.next = 5;
return getDocumentByQuery(Master, {
_id: id
});
case 5:
masterData = _context2.sent;
if (!masterData.parentId) {
_context2.next = 9;
break;
}
_context2.next = 9;
return bulkUpdate(Master, {
parentId: masterData.parentId,
isDefault: true
}, {
isDefault: false
});
case 9:
_context2.next = 11;
return findOneAndUpdateDocument(Master, {
_id: id
}, data, {
"new": true
}, {
path: 'img',
select: 'uri'
});
case 11:
_context2.next = 13;
return Master.findOne({
_id: id
});
case 13:
result = _context2.sent;
if (!result) {
_context2.next = 18;
break;
}
section = result.parentCode ? 'submaster' : 'master';
res.message = req == null ? void 0 : (_req$i18n2 = req.i18n) == null ? void 0 : _req$i18n2.t(section + ".update");
return _context2.abrupt("return", successResponse(result, res));
case 18:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x3, _x4) {
return _ref2.apply(this, arguments);
};
}());
var activateMaster = /*#__PURE__*/catchAsync( /*#__PURE__*/function () {
var _ref3 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, res) {
var id, data, result, section, _req$i18n3, _req$i18n4;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
id = req.params.id;
data = req.body;
_context3.next = 4;
return findOneAndUpdateDocument(Master, {
_id: id
}, data, {
"new": true
}, {
path: 'img',
select: 'uri'
});
case 4:
result = _context3.sent;
section = result.parentCode ? 'submaster' : 'master';
if (result.isActive) {
res.message = req == null ? void 0 : (_req$i18n3 = req.i18n) == null ? void 0 : _req$i18n3.t(section + ".activate");
} else {
res.message = req == null ? void 0 : (_req$i18n4 = req.i18n) == null ? void 0 : _req$i18n4.t(section + ".deactivate");
}
return _context3.abrupt("return", successResponse(result, res));
case 8:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x5, _x6) {
return _ref3.apply(this, arguments);
};
}());
var webVisibleMaster = /*#__PURE__*/catchAsync( /*#__PURE__*/function () {
var _ref4 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, res) {
var id, data, result, section, _req$i18n5, _req$i18n6;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
id = req.params.id;
data = req.body;
_context4.next = 4;
return findOneAndUpdateDocument(Master, {
_id: id
}, data, {
"new": true
}, {
path: 'img',
select: 'uri'
});
case 4:
result = _context4.sent;
section = result.parentCode ? 'submaster' : 'master';
if (result.isWebVisible) {
res.message = req == null ? void 0 : (_req$i18n5 = req.i18n) == null ? void 0 : _req$i18n5.t(section + ".display");
} else {
res.message = req == null ? void 0 : (_req$i18n6 = req.i18n) == null ? void 0 : _req$i18n6.t(section + ".notDisplay");
}
return _context4.abrupt("return", successResponse(result, res));
case 8:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return function (_x7, _x8) {
return _ref4.apply(this, arguments);
};
}());
var defaultMaster = /*#__PURE__*/catchAsync( /*#__PURE__*/function () {
var _ref5 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req, res) {
var result, section, _req$i18n7, _req$i18n8;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return defaultMaster$1(req.params.id, req.body);
case 2:
result = _context5.sent;
section = result.parentCode ? 'submaster' : 'master';
if (result.isDefault) {
res.message = req == null ? void 0 : (_req$i18n7 = req.i18n) == null ? void 0 : _req$i18n7.t(section + ".default");
} else {
res.message = req == null ? void 0 : (_req$i18n8 = req.i18n) == null ? void 0 : _req$i18n8.t(section + ".notDefault");
}
return _context5.abrupt("return", successResponse(result, res));
case 6:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function (_x9, _x10) {
return _ref5.apply(this, arguments);
};
}());
var sequenceMaster = /*#__PURE__*/catchAsync( /*#__PURE__*/function () {
var _ref6 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, res) {
var _req$i18n9;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return sequenceMaster$1(req.body.sequences);
case 2:
res.message = req == null ? void 0 : (_req$i18n9 = req.i18n) == null ? void 0 : _req$i18n9.t('submaster.seq');
return _context6.abrupt("return", successResponse({}, res));
case 5:
case "end":
return _context6.stop();
}
}
}, _callee6);
}));
return function (_x