处理了endpoint的注入

This commit is contained in:
Xu Chang 2023-01-19 22:50:37 +08:00
parent 1c2acf8bb8
commit d34634788b
2 changed files with 66 additions and 1 deletions

View File

@ -64,6 +64,38 @@ async function startup(path, contextBuilder, connector, omitWatchers, omitTimers
ctx.response.body = body;
return;
});
// 注入所有的endpoints
const endpoints = appLoader.getEndpoints();
const endpointsArray = [];
for (const ep in endpoints) {
const { method, fn, params, name } = endpoints[ep];
let url = `/endpoint/${ep}`;
if (params) {
for (const p of params) {
url += `/:${p}`;
}
}
endpointsArray.push([name, url]);
router[method](name, url, async (ctx) => {
const { req, request, params } = ctx;
const { body, headers } = request;
const context = await contextBuilder()(appLoader.getStore());
await context.begin();
try {
const result = await fn(context, params, headers, req, body);
await context.commit();
ctx.response.body = result;
return;
}
catch (err) {
await context.rollback();
throw err;
}
});
}
router.get('/endpoint', async (ctx) => {
ctx.response.body = endpointsArray;
});
koa.use(router.routes());
const serverConfig = require(path_1.default.join(path, '/configuration/server.json'));
console.log(`server will listen on port ${serverConfig.port}`);

View File

@ -71,8 +71,41 @@ export async function startup<ED extends EntityDict & BaseEntityDict, Cxt extend
ctx.response.body = body;
return;
});
koa.use(router.routes());
// 注入所有的endpoints
const endpoints = appLoader.getEndpoints();
const endpointsArray: [string, string][] = [];
for (const ep in endpoints) {
const { method, fn, params, name } = endpoints[ep];
let url = `/endpoint/${ep}`;
if (params) {
for (const p of params) {
url += `/:${p}`;
}
}
endpointsArray.push([name, url]);
router[method](name, url, async (ctx) => {
const { req, request, params } = ctx;
const { body, headers } = request;
const context = await contextBuilder()(appLoader.getStore());
await context.begin();
try {
const result = await fn(context, params, headers, req, body);
await context.commit();
ctx.response.body = result;
return;
}
catch(err) {
await context.rollback();
throw err;
}
});
}
router.get('/endpoint', async (ctx) => {
ctx.response.body = endpointsArray;
});
koa.use(router.routes());
const serverConfig = require(PathLib.join(path, '/configuration/server.json'));
console.log(`server will listen on port ${serverConfig.port}`);