@mahhoura/fastify-autoroutes
Version:
Map directory structure to routes
83 lines • 3.91 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ERROR_LABEL = void 0;
const error_1 = __importDefault(require("@fastify/error"));
const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
const fs_1 = __importDefault(require("fs"));
const glob_1 = require("glob");
const path_1 = __importDefault(require("path"));
const process_1 = __importDefault(require("process"));
exports.ERROR_LABEL = 'fastify-autoroutes';
exports.default = (0, fastify_plugin_1.default)((fastify, options, next) => __awaiter(void 0, void 0, void 0, function* () {
const { dir, prefix: routePrefix } = Object.assign(Object.assign({}, options), { dir: options.dir || './routes', prefix: options.prefix || '' });
let dirPath;
if (path_1.default.isAbsolute(dir)) {
dirPath = dir;
}
else if (path_1.default.isAbsolute(process_1.default.argv[1])) {
dirPath = path_1.default.join(process_1.default.argv[1], dir);
}
else {
dirPath = path_1.default.join(process_1.default.cwd(), process_1.default.argv[1], dir);
}
if (!fs_1.default.existsSync(dirPath)) {
const CustomError = (0, error_1.default)('1', `${exports.ERROR_LABEL} dir ${dirPath} must be a directory`);
return next(new CustomError());
}
if (!fs_1.default.statSync(dirPath).isDirectory()) {
const CustomError = (0, error_1.default)('2', `${exports.ERROR_LABEL} dir ${dirPath} must be a directory`);
return next(new CustomError());
}
// glob returns ../../, but windows returns ..\..\
dirPath = path_1.default.normalize(dirPath).replace(/\\/g, '/');
const routes = yield (0, glob_1.glob)(`${dirPath}/**/[!._]!(*.test).{ts,js}`);
const routesModules = {};
// console.log({ routes })
for (const route of routes) {
let routeName = route
.replace(dirPath, '')
.replace('.js', '')
.replace('.ts', '')
.replace('index', '')
.split('/')
.map((part) => part.replace(/{(.+)}/g, ':$1'))
.join('/');
routeName = !routeName ? '/' : `${routePrefix}${routeName}`;
// console.log({ routeName })
routesModules[routeName] = loadModule(routeName, route)(fastify);
}
for (const [url, module] of Object.entries(routesModules)) {
for (const [method, options] of Object.entries(module)) {
fastify.route(Object.assign({ method: method.toUpperCase(), url: url }, options));
}
}
}), {
fastify: '>=4.0.0',
name: 'fastify-autoroutes',
});
function loadModule(name, path) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const module = require(path);
if (typeof module === 'function') {
return module;
}
if (typeof module === 'object' &&
'default' in module &&
typeof module.default === 'function') {
return module.default;
}
throw new Error(`${exports.ERROR_LABEL}: invalid route module definition (${name}) ${path}. Must export a function`);
}
//# sourceMappingURL=index.js.map