Files
core_ng/server/api/serverAPI.ts
T
2023-08-06 05:49:25 +00:00

29 lines
1.0 KiB
TypeScript

import { Router } from 'express';
import type { APIExecuter, APINamespace } from './base.js';
export function buildAPISystem<N extends APINamespace, Q extends APIExecuter<any, any, any>>(api: N | Q): Router {
const router = Router();
for (const [key, value] of Object.entries(api)) {
if (typeof value === 'function') {
const executer = new value() as Q;
if(!executer.reqType){
throw new Error('APIExecuter.reqType is not defined');
}
if(!Array.isArray(executer.reqType)){
router[executer.reqType](key, async (req, res) => {
await executer.run(req, res);
});
continue;
}
for(const type of new Set(executer.reqType)){
router[type](key, async (req, res) => {
await executer.run(req, res);
});
}
} else {
router.use(key, buildAPISystem(value));
}
}
return router;
}