Skip to content
This repository was archived by the owner on Aug 28, 2023. It is now read-only.

Commit 3639983

Browse files
committed
refactor: parse and mount route when routes was called.
to avoid plugin not mount finish, but the route was mounted.
1 parent 82f60e9 commit 3639983

File tree

3 files changed

+84
-2
lines changed

3 files changed

+84
-2
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "koa-oai-router",
3-
"version": "2.0.0-alpha.3",
3+
"version": "2.0.0-alpha.4",
44
"main": "lib",
55
"scripts": {
66
"clean": "rm -rf coverage lib",

src/router.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,16 @@ class OAIRouter extends Router {
2828
this.api = null;
2929
this.pluginRegister = new PluginRegister(this.options);
3030

31-
spec(apiDoc)
31+
this.apiDoc = apiDoc;
32+
}
33+
34+
/**
35+
* Start to parse apiDoc and mount routes. Must called after all mount action is finished.
36+
* @public
37+
* @returns route dispatcher, koa middleware
38+
*/
39+
routes() {
40+
spec(this.apiDoc)
3241
.then(async (api) => {
3342
this.api = api;
3443

@@ -43,6 +52,8 @@ class OAIRouter extends Router {
4352

4453
this.emit('error', error);
4554
});
55+
56+
return super.routes();
4657
}
4758

4859
/**

test/plugin/plugin.multi.test.js

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { init, Plugin } from '../helpers';
2+
3+
describe('Plugin multi', () => {
4+
it('multi plugin, should success', async () => {
5+
class PluginX extends Plugin {
6+
constructor() {
7+
super();
8+
9+
this.field = 'parameters';
10+
}
11+
handler() {
12+
const { args } = this;
13+
14+
return (ctx, next) => {
15+
ctx.value = args;
16+
17+
return next();
18+
};
19+
}
20+
}
21+
22+
class PluginY extends Plugin {
23+
constructor() {
24+
super();
25+
26+
this.field = 'parameters';
27+
}
28+
handler() {
29+
const { args } = this;
30+
31+
return (ctx, next) => {
32+
ctx.value += args;
33+
34+
return next();
35+
};
36+
}
37+
}
38+
39+
class PluginZ extends Plugin {
40+
constructor() {
41+
super();
42+
43+
this.field = 'parameters';
44+
}
45+
handler() {
46+
const { args } = this;
47+
48+
return (ctx, next) => {
49+
ctx.value += args;
50+
51+
ctx.response.body = ctx.value;
52+
};
53+
}
54+
}
55+
56+
const { request } = await init({
57+
apiDoc: './test/plugin/api',
58+
plugins: [PluginX, PluginY, PluginZ],
59+
options: {
60+
PluginX: 'x',
61+
PluginY: 'y',
62+
PluginZ: 'z',
63+
},
64+
});
65+
66+
await request
67+
.get('/api/pets')
68+
.expect(200)
69+
.expect('xyz');
70+
});
71+
});

0 commit comments

Comments
 (0)