-
Notifications
You must be signed in to change notification settings - Fork 568
/
fav.middleware.ts
48 lines (40 loc) 路 1.18 KB
/
fav.middleware.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
import { Config, Middleware } from '@midwayjs/core';
const path = require('path');
const MAX_AGE = 'public, max-age=2592000'; // 30 days
@Middleware()
export class SiteFileMiddleware {
@Config('siteFile')
siteFileConfig;
resolve() {
// use bodyparser middleware
if (this.siteFileConfig.enable) {
return async (ctx, next) => {
if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return next();
/* istanbul ignore if */
if (ctx.path[0] !== '/') return next();
if (ctx.path !== '/favicon.ico') {
return next();
}
let content = this.siteFileConfig['favicon'];
if (content === undefined) {
content = Buffer.from('');
}
if (!content) return next();
// content is url
if (typeof content === 'string') return ctx.redirect(content);
// '/robots.txt': Buffer <xx..
// content is buffer
if (Buffer.isBuffer(content)) {
ctx.set('cache-control', MAX_AGE);
ctx.body = content;
ctx.type = path.extname(ctx.path);
return;
}
return next();
};
}
}
static getName() {
return 'siteFile';
}
}