-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (50 loc) · 1.63 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
63
64
65
66
'use strict';
module.exports = addTrailingSlashes;
function addTrailingSlashes(opts) {
opts = opts || {};
if (opts.defer !== false) {
opts.defer = opts.defer || true;
}
if (opts.index !== false) {
opts.index = opts.index || 'index.html';
}
if (opts.chained !== false) {
opts.chained = opts.chained || true;
}
return async function(ctx, next) {
if (opts.defer) {
await next();
}
let path;
// We have already done a redirect and we will continue if we are in chained mode
if (opts.chained && ctx.status === 301) {
path = getPath(ctx.response.get('Location'), ctx.querystring);
} else if (ctx.status !== 301) {
path = getPath(ctx.originalUrl, ctx.querystring);
}
if (path && noBodyOrIndex(ctx.status, ctx.body, path, opts.index) && missingSlash(path)) {
const query = ctx.querystring.length ? '?' + ctx.querystring : '';
ctx.status = 301;
ctx.redirect(path + '/' + query);
}
if (!opts.defer) {
await next();
}
};
}
function getFilename(path) {
return path.replace(/^.*[\\\/]/, '');
}
function noBodyOrIndex(status, body, path, index) {
return !body || status !== 200 ||
(index && body.path && getFilename(body.path) === index && getFilename(body.path) !== getFilename(path));
}
function missingSlash(path) {
return path.slice(-1) !== '/';
}
function getPath(original, querystring) {
if (querystring.length) {
return original.slice(0, -querystring.length - 1);
}
return original;
}