-
Notifications
You must be signed in to change notification settings - Fork 568
/
swaggerMiddleware.ts
97 lines (87 loc) 路 2.57 KB
/
swaggerMiddleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import {
IMiddleware,
IMidwayApplication,
IMidwayContext,
NextFunction,
Config,
Init,
Inject,
Provide,
Scope,
ScopeEnum,
MidwayEnvironmentService,
MidwayInvalidConfigPropertyError,
} from '@midwayjs/core';
import type { SwaggerOptions } from './interfaces';
import { SwaggerExplorer } from './swaggerExplorer';
@Provide()
@Scope(ScopeEnum.Singleton)
export class SwaggerMiddleware
implements IMiddleware<IMidwayContext, NextFunction, unknown>
{
@Config('swagger')
private swaggerConfig: SwaggerOptions;
private swaggerRender: (
pathname: string
) => Promise<{ ext: string; content: string }>;
@Inject()
private swaggerExplorer: SwaggerExplorer;
@Inject()
environmentService: MidwayEnvironmentService;
@Init()
async init() {
if (typeof this.swaggerConfig.swaggerUIRender !== 'function') {
throw new MidwayInvalidConfigPropertyError('swagger.swaggerRender');
}
this.swaggerRender = this.swaggerConfig.swaggerUIRender(
this.swaggerConfig,
this.swaggerExplorer
);
}
resolve(app: IMidwayApplication) {
if (app.getNamespace() === 'express') {
return async (req: any, res: any, next: NextFunction) => {
const pathname = req.path;
const renderResult = await this.swaggerRender(pathname);
if (renderResult) {
const { ext, content } = renderResult;
if (ext === '.js') {
res.type('application/javascript');
} else if (ext === '.map') {
res.type('application/json');
} else if (ext === '.css') {
res.type('text/css');
} else if (ext === '.png') {
res.type('image/png');
}
res.send(content);
} else {
return next();
}
};
} else {
return async (ctx: IMidwayContext, next: NextFunction) => {
const pathname = (ctx as any).path;
const renderResult = await this.swaggerRender(pathname);
if (renderResult) {
const { ext, content } = renderResult;
if (ext === '.js') {
(ctx as any).set('Content-Type', 'application/javascript');
} else if (ext === '.map') {
(ctx as any).set('Content-Type', 'application/json');
} else if (ext === '.css') {
(ctx as any).set('Content-Type', 'text/css');
} else if (ext === '.png') {
(ctx as any).set('Content-Type', 'image/png');
}
(ctx as any).body = content;
} else {
return next();
}
};
}
}
static getName() {
return 'swagger';
}
}