Skip to content

Commit ddc1716

Browse files
committed
feat(test): 添加Koa框架支持并更新相关测试
1 parent f5adf2b commit ddc1716

File tree

4 files changed

+38
-37
lines changed

4 files changed

+38
-37
lines changed

package.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,15 @@
5252
"@types/express": "^4.17.21",
5353
"@types/jest": "^27.5.2",
5454
"@types/koa": "^2.15.0",
55+
"@types/koa-bodyparser": "^4.3.12",
56+
"@types/koa-router": "^7.4.8",
5557
"@types/supertest": "^2.0.16",
5658
"coveralls": "^3.1.1",
5759
"express": "^4.18.2",
5860
"jest": "^27.5.1",
5961
"koa": "^3.0.0",
62+
"koa-bodyparser": "^4.4.1",
63+
"koa-router": "^13.0.1",
6064
"prettier": "^2.8.8",
6165
"supertest": "^6.3.4",
6266
"ts-jest": "^27.1.5",

src/lib/index.ts

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -493,32 +493,6 @@ export default class ERest<T = DEFAULT_HANDLER> {
493493
);
494494
}
495495
}
496-
497-
public bindRouterToKoa(router: any, checker: (erest: ERest<T>, schema: API<T>) => T) {
498-
if (this.forceGroup) {
499-
throw this.error.internalError("使用了 forceGroup,请使用 bindKoaRouterToApp");
500-
}
501-
for (const [key, schema] of this.apiInfo.$apis.entries()) {
502-
debug("bind router to koa: %s", key);
503-
schema.init(this as unknown as ERest<T>);
504-
505-
const handlers = [
506-
...(this.apiInfo.beforeHooks as any), // Spread Set into array
507-
...(schema.options.beforeHooks as any), // Spread Set into array
508-
checker(this as unknown as ERest<T>, schema as API<T>),
509-
...(schema.options.middlewares as any), // Spread Set into array
510-
schema.options.handler,
511-
].filter(h => typeof h === 'function'); // Ensure only functions are passed
512-
513-
const routeMethod = schema.options.method.toLowerCase();
514-
if (typeof router[routeMethod] === 'function') {
515-
router[routeMethod](schema.options.path, ...handlers);
516-
} else {
517-
console.error(`ERest: Invalid method ${routeMethod} for Koa router.`);
518-
}
519-
}
520-
}
521-
522496
public bindKoaRouterToApp(app: any, KoaRouter: any, checker: (erest: ERest<T>, schema: API<T>) => T) {
523497
if (!this.forceGroup) {
524498
throw this.error.internalError("没有开启 forceGroup,请使用 bindRouterToKoa");

src/test/test-group.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import express from "express";
2-
import { Application, Router, Context } from "@leizm/web";
2+
import { Application, Router, Context as LeiContext } from "@leizm/web";
3+
import Koa ,{Context as KoaContext} from 'koa';
4+
import KoaRouter from 'koa-router'; // or import Router from 'koa-router';
5+
// import bodyParser from 'koa-bodyparser'; // Add this
36

47
import { hook } from "./helper";
58
import lib from "./lib";
@@ -8,10 +11,14 @@ function reqFn(req: express.Request, res: express.Response) {
811
res.json("Hello, API Framework Index");
912
}
1013

11-
function reqFnLeiWeb(ctx: Context) {
14+
function reqFnLeiWeb(ctx: LeiContext) {
1215
ctx.response.json("Hello, API Framework Index");
1316
}
1417

18+
function reqFnKoa(ctx: KoaContext) {
19+
ctx.response.body = "Hello, API Framework Index";
20+
}
21+
1522
const globalBefore = hook("globalBefore");
1623
const globalAfter = hook("globalAfter");
1724
const beforHook = hook("beforHook");
@@ -127,6 +134,22 @@ describe("Group - 使用@leizm/web框架", () => {
127134
});
128135
});
129136

137+
describe("Group - 使用koa框架", () => {
138+
const apiService = lib({ forceGroup: true, info: { basePath: "" } });
139+
const api = apiService.group("Index");
140+
const app = new Koa();
141+
api.get("/").title("Get").register(reqFnKoa);
142+
apiService.bindKoaRouterToApp(app, KoaRouter, apiService.checkerKoa);
143+
144+
test("Get请求成功", async () => {
145+
apiService.initTest(app.callback());
146+
147+
const { text: ret } = await apiService.test.get("/index/").raw();
148+
expect(ret).toBe("Hello, API Framework Index");
149+
});
150+
});
151+
152+
130153
describe("Group - 高级分组配置", () => {
131154
const apiService = lib({
132155
forceGroup: true,

src/test/test-koa.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import Koa from 'koa';
22
import KoaRouter from 'koa-router'; // or import Router from 'koa-router';
33
import request from 'supertest';
44
import bodyParser from 'koa-bodyparser'; // Add this
5-
import ERest, { KoaHandler, API } from '../lib'; // Adjust path as needed
5+
import ERest from '../lib'; // Adjust path as needed
66

77
// Helper to set up ERest instance for forceGroup: false
88
const setupERestNoGroup = () => {
9-
return new ERest<KoaHandler>({
9+
return new ERest({
1010
info: { title: 'Koa Test No Group' },
1111
// Ensure default error handlers are set up if your tests rely on specific status codes for errors
1212
missingParameterError: (msg: string) => ({ status: 400, message: `Missing Parameter: ${msg}` } as any), // Example
@@ -16,7 +16,7 @@ const setupERestNoGroup = () => {
1616

1717
// Helper to set up ERest instance for forceGroup: true
1818
const setupERestWithGroup = () => {
19-
return new ERest<KoaHandler>({
19+
return new ERest({
2020
info: { title: 'Koa Test With Group' },
2121
forceGroup: true,
2222
groups: {
@@ -35,22 +35,22 @@ describe('ERest Koa Integration', () => {
3535
app.use(bodyParser()); // Use bodyParser for all non-group tests
3636
const erest = setupERestNoGroup();
3737
const router = new KoaRouter();
38-
38+
const api = erest.group("Index");;
3939
// Test 1.1
40-
erest.api.get('/test-koa').register(async (ctx: Koa.Context) => { ctx.body = { success: true, data: 'koa works' }; });
40+
api.get('/test-koa').register(async (ctx: Koa.Context) => { ctx.body = { success: true, data: 'koa works' }; });
4141

4242
// Test 1.2
43-
erest.api.get('/query-test')
43+
api.get('/query-test')
4444
.query({ name: { type: 'string', required: true }})
4545
.register(async (ctx: Koa.Context) => { ctx.body = { name: (ctx.request as any).$params.query.name }; });
4646

4747
// Test 1.3
48-
erest.api.post('/body-test')
48+
api.post('/body-test')
4949
.body({ id: { type: 'int', required: true }})
5050
.register(async (ctx: Koa.Context) => { ctx.body = { id: (ctx.request as any).$params.body.id }; });
5151

5252
// After all API definitions for this block
53-
erest.bindRouterToKoa(router, (e,s) => erest.checkerKoa(e,s as API<KoaHandler>));
53+
erest.bindRouterToKoa(router, (e,s) => erest.checkerKoa(e,s));
5454
app.use(router.routes()).use(router.allowedMethods());
5555

5656
// Now run the actual test executions that were commented out above
@@ -79,7 +79,7 @@ describe('ERest Koa Integration', () => {
7979
erestGroup.group('user').get('/info').register(async (ctx: Koa.Context) => { ctx.body = { group: 'user info' }; });
8080

8181
// After all API definitions for this block
82-
erestGroup.bindKoaRouterToApp(appGroup, KoaRouter, (e,s) => erestGroup.checkerKoa(e,s as API<KoaHandler>));
82+
erestGroup.bindKoaRouterToApp(appGroup, KoaRouter, (e,s) => erestGroup.checkerKoa(e,s));
8383

8484
// Now run the actual test executions
8585
it('should handle basic GET request in a group with explicit prefix (execution)', async () => {

0 commit comments

Comments
 (0)