@tasolutions/express-core
Version:
All libs for express
78 lines (71 loc) • 2.5 kB
JavaScript
;
const mongoose = require('mongoose');
const _ = require('lodash');
const actionList = require('./actionList');
module.exports = {
setAction: (modelName, action, method, path, includes = []) => {
let controllerKey;
let key;
if (typeof modelName === 'string') {
return (req, res, next) => {
req.model_name = modelName.toLowerCase();
next();
};
} else if (modelName instanceof mongoose.Model) {
controllerKey = modelName.modelName.toUpperCase();
} else if (typeof modelName === 'object') {
const keys = Object.keys(modelName);
if (keys.length > 0) {
controllerKey = keys[0].toUpperCase();
} else {
throw new Error('Invalid modelName: empty object provided.');
}
} else {
throw new Error('Invalid modelName: must be a string, a mongoose Model instance, or an object.');
}
key = `${controllerKey}_${action}`.toUpperCase();
let type;
switch (method.toUpperCase()) {
case 'POST':
type = 'CREATE';
break;
case 'GET':
const pathSegments = path.split('/');
const lastSegment = pathSegments[pathSegments.length - 1];
if (lastSegment.includes(':')) {
type = 'DETAIL';
} else if (pathSegments.length === 3 || pathSegments.length === 4) {
type = 'LIST';
} else {
type = 'UNKNOW';
}
break;
case 'PUT':
type = 'UPDATE';
break;
case 'DELETE':
type = 'DELETE';
break;
default:
type = 'UNKNOW';
}
actionList.push({
collection_key: controllerKey.toLowerCase(),
controller: controllerKey,
controller_name: _.startCase(controllerKey.toLowerCase()),
key,
name: _.startCase(`${controllerKey} ${action}`.toLowerCase()),
action: action?.toLowerCase(),
path,
method,
type,
is_extend: true,
includes,
});
return (req, res, next) => {
req.key = key;
req.model_name = controllerKey.toLowerCase();
next();
}
}
}