-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
54 lines (41 loc) · 1.29 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
'use strict';
const normalize = require('path').posix.normalize;
module.exports = normalizePath;
function normalizePath(opts) {
opts = opts || {};
if (opts.defer !== false) {
opts.defer = opts.defer || true;
}
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) {
const normalizedPath = normalize(path);
if (path !== normalizedPath) {
const query = ctx.querystring.length ? '?' + ctx.querystring : '';
ctx.status = 301;
ctx.redirect(normalizedPath + query);
}
}
if (!opts.defer) {
await next();
}
};
}
function getPath(original, querystring) {
if (querystring.length) {
return original.slice(0, -querystring.length - 1);
}
return original;
}