-
Notifications
You must be signed in to change notification settings - Fork 568
/
jsonp.ts
56 lines (51 loc) 路 1.34 KB
/
jsonp.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
import {
Config,
Middleware,
MidwayFrameworkType,
Match,
IMiddleware,
} from '@midwayjs/core';
import { JSONPService } from '../jsonp';
import { JSONPCSRFError } from '../error';
import { JSONPOptions } from '../interface';
@Match()
export class JSONPFilter {
async match(value, req) {
const jsonpService = await req.requestContext.getAsync(JSONPService);
return jsonpService.jsonp(value);
}
}
@Middleware()
export class JSONPMiddleware implements IMiddleware<any, any> {
@Config('jsonp')
jsonp: JSONPOptions;
resolve(app) {
if (app.getFrameworkType() === MidwayFrameworkType.WEB_EXPRESS) {
app.useFilter(JSONPFilter);
return async (req: any, res: any, next: any) => {
return this.compatibleMiddleware(req, next);
};
} else {
return async (ctx, next) => {
const result = await this.compatibleMiddleware(ctx, next);
const jsonpService = await ctx.requestContext.getAsync(JSONPService);
return jsonpService.jsonp(result);
};
}
}
async compatibleMiddleware(context, next) {
const { csrf } = this.jsonp;
// midway security
if (csrf && context.assertCsrf) {
try {
context.assertCsrf();
} catch (_) {
throw new JSONPCSRFError();
}
}
return await next();
}
static getName(): string {
return 'jsonp';
}
}