-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
62 lines (50 loc) · 1.75 KB
/
index.js
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
const _ = require('lodash');
const ms = require('ms');
const { pathToRegexp } = require('path-to-regexp');
class CacheResponses {
constructor(config = {}) {
this.config = {
pathToRegexp: { sensitive: true, strict: true },
routes: [],
// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control>
// <https://web.dev/uses-long-cache-ttl/?utm_source=lighthouse&utm_medium=unknown>
cacheControl: ['public', `max-age=${ms('1y') / 1000}`],
methods: ['HEAD', 'GET'],
...config
};
this.middleware = this.middleware.bind(this);
this.paired = this.paired.bind(this);
}
async middleware(ctx, next) {
if (!this.config.methods.includes(ctx.method)) return next();
if (!_.isFunction(ctx.cashed))
throw new Error(
'Please ensure you have set up `koa-cash` properly, see https://github.com/koajs/cash for more info.'
);
const { path } = ctx.request;
let match = false;
for (let i = 0; i < this.config.routes.length; i++) {
let route = this.config.routes[i];
if (_.isObject(this.config.routes[i])) route = this.config.routes[i].path;
if (this.paired(route, path)) {
match = true;
break;
}
}
if (!match) return next();
// inspired by @redpill-paris/koa-cache-control
// <https://github.com/RedPillGroup/koa-cache-control>
if (
Array.isArray(this.config.cacheControl) &&
this.config.cacheControl.length > 0
)
ctx.set('Cache-Control', this.config.cacheControl.join(', '));
const cashed = await ctx.cashed();
if (cashed) return;
return next();
}
paired(route, path) {
return pathToRegexp(route, [], this.config.pathToRegexp).exec(path);
}
}
module.exports = CacheResponses;