@backapirest/express
Version:
A simple API framework using Flexible Persistence
81 lines • 2.83 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = require("node:fs/promises");
const verbose = JSON.parse((process.env.BACK_API_REST_DEBUG || 'false').toLowerCase());
const isFile = (file) => {
return file.includes('.ts') || file.includes('.js');
};
const isIndexFile = (file) => {
return file.includes('index.ts') || file.includes('index.js');
};
const isParamFile = (file) => {
return file.includes('].ts') || file.includes('].js');
};
const getParam = (file) => {
return file?.split(/\]\.(t|j)s/)?.[0]?.split('[')?.[1];
};
const getHandlerName = async (path) => {
const files = await (0, promises_1.readdir)(path);
const handler = files.filter((file) => file.includes('Handler.ts') || file.includes('Handler.js'))[0];
return handler;
};
const getRequestHandler = (file) => {
return file
.split(/request\)*\(/)[1]
.split(');')[0]
.split("'")[1];
};
const getHandler = async (path, handler) => {
if (path !== undefined && handler !== undefined && handler !== null) {
let name = await (0, promises_1.readFile)(path + '/' + handler, { encoding: 'utf8' });
name = getRequestHandler(name);
return name;
}
return undefined;
};
const readFolder = async (path, router, roots) => {
let read = false;
const errors = [];
for (const root of roots) {
const realPath = root !== undefined ? root + '/' + path : path;
try {
const files = await (0, promises_1.readdir)(realPath);
const handler = await getHandler(realPath, await getHandlerName(realPath));
for (const file of files) {
if (isFile(file) && handler !== undefined)
await readFile(path, file, handler, router);
else if (!isFile(file))
await readFolder(path + '/' + file, router, [root]);
}
read = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}
catch (error) {
errors.push(error);
}
}
if (!read && verbose) {
console.error('Error reading: ' + path);
console.error(errors);
}
};
const readFile = async (path, file, handler, router) => {
const isIndex = isIndexFile(file);
const param = !isIndex && isParamFile(file) ? getParam(file) : undefined;
const route = '/' + path + (param !== undefined ? `:${param}` : '');
router.addRoute(route, handler);
};
const execute = async (router) => await readFolder('api', router, [
'.',
'./src',
'./source',
'./src/pages',
'./source/pages',
'./dist',
'./dist/src',
'./dist/source',
'./dist/src/pages',
'./dist/source/pages',
]);
exports.default = execute;
//# sourceMappingURL=loader.js.map
;