-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (53 loc) · 1.44 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
67
68
69
70
71
72
/*!
* trek-method-override
* Copyright(c) 2017 Fangdun Cai <[email protected]> (https://fundon.me)
* MIT Licensed
*/
'use strict'
const { METHODS } = require('http')
const vary = require('vary')
const defaults = {
methods: ['POST'],
tokenLookup: 'header:X-HTTP-Method-Override'
}
module.exports = methodOverrideWithConfig
function methodOverrideWithConfig (options = {}) {
options = Object.assign({}, defaults, options)
const { methods, tokenLookup } = options
const [via, field] = tokenLookup.split(':')
let extractor = methodFromHeader
switch (via) {
case 'form':
extractor = methodFromForm
break
case 'query':
extractor = methodFromQuery
break
// No default
}
return methodOverride
function methodOverride ({ req, rawRes }, next) {
req.originalMethod = req.originalMethod || req.method
if (methods.includes(req.originalMethod)) {
let m = extractor(field, req, rawRes)
if (Array.isArray(m)) m = m[0]
if (m) {
m = m.toUpperCase()
if (METHODS.includes(m)) req.method = m
}
}
return next()
}
}
function methodFromHeader (header, req, rawRes) {
// Set appropriate Vary header
vary(rawRes, header)
// Multiple headers get joined with comma by node core
return (req.get(header) || '').split(/ *, */)
}
function methodFromForm (param, req) {
return req.body[param]
}
function methodFromQuery (param, req) {
return req.query[param]
}