-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (43 loc) · 1.26 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
'use strict';
const { URL } = require('url');
const { resolve } = require('path');
module.exports = resolvePath;
/**
* default options
*
* @type {Object}
* @property {Array|string} methods method to apply
*/
const defaults = {
methods: 'GET',
};
/**
* Rewrite middleware to apply resolve path
*
* @param {Object} options resolvePath options
* @returns {Function} resolvePath middleware
*/
function resolvePath(options = {}) {
const opts = Object.assign({}, defaults, options);
// 'GET' => ['GET'], 'GET POST' => ['GET', 'POST']
if (typeof opts.methods === 'string') {
opts.methods = opts.methods.trim().split(' ');
}
// convert to upper case
const methods = opts.methods.map(val => val.toUpperCase());
return function resolvePath(req, res, next) {
if (methods.includes(req.method.toUpperCase())) {
const origin = `${req.protocol}://${req.hostname}`;
// by parseurl
const { pathname, search } = req._parsedUrl;
const processed = resolve(pathname) + (search || '');
// WHATWG URL Standard
const parsed = new URL(processed, origin);
req._resolveOriginalUrl = req.url;
req._resolveParsedUrl = parsed;
// path rewrite
req.url = parsed.pathname + parsed.search;
}
next();
};
}