Files
system-builder/src/views/routes-creator.ts

76 lines
2.3 KiB
TypeScript

import {EndpointDef} from "../systemGenService";
import {lowercaseFirstLetter, uppercaseFirstLetter} from "../helpers";
import {buildServiceFunctionName, getFuncParams} from "./service-creator";
import pluralize from "pluralize";
const METHOD = {
'count': 'post',
'create': 'post',
'delete': 'delete',
'item': 'get',
'list': 'post',
'search': 'post',
'update': 'put',
}
const URL = {
'count': (view: EndpointDef) => {
return `count${uppercaseFirstLetter(pluralize(view.component))}`;
},
'create': (view: EndpointDef) => {
return `${view.component}`;
},
'delete': (view: EndpointDef) => {
// TODO: needs the params added to select the right one (id)
return `${view.component}/:${view.component}_id`;
},
'item': (view: EndpointDef) => {
// TODO: needs the params added to select the right one (id)
return `${view.component}/:${view.component}_id`;
},
'list': (view: EndpointDef) => {
return `${pluralize(view.component)}`;
},
'search': (view: EndpointDef) => {
return `search${uppercaseFirstLetter(pluralize(view.component))}`;
},
'update': (view: EndpointDef) => {
// TODO: needs the params added to select the right one (id)
return `${view.component}/:${view.component}_id`;
},
}
function createRoutesFunc(view: EndpointDef): string {
let params = getFuncParams(view);
let isListOrSearch: boolean = view.type === 'list' || view.type === 'search';
if (isListOrSearch) {
params.push('offset');
params.push('limit');
}
// TODO: get requests don't have req.body so the params need to come from the url
let func: string = `
router.${METHOD[view.type]}('/${URL[view.type](view)}', (req, res, next) => {
${serviceInstance(view)}.${buildServiceFunctionName(view)}(${(params.length ? 'req.body.' : '') + params.join(', req.body.')}).then((data) => {
res.status(200);
res.json(data);
}).catch((err) => {
res.status(500);
res.json({
status: 'error',
message: err,
});
});
});
`;
return func;
}
function serviceInstance(view: EndpointDef): string {
return `${lowercaseFirstLetter(view.component)}Service`;
}
export {
createRoutesFunc,
METHOD,
URL
}