1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | var debug = require('debug')('method-override')
|
15 | var methods = require('methods');
|
16 | var parseurl = require('parseurl');
|
17 | var querystring = require('querystring');
|
18 | var vary = require('vary');
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | module.exports = function methodOverride(getter, options){
|
43 | options = options || {}
|
44 |
|
45 |
|
46 | var get = typeof getter === 'function'
|
47 | ? getter
|
48 | : createGetter(getter || 'X-HTTP-Method-Override')
|
49 |
|
50 | // get allowed request methods to examine
|
51 | var methods = options.methods === undefined
|
52 | ? ['POST']
|
53 | : options.methods
|
54 |
|
55 | return function methodOverride(req, res, next) {
|
56 | var method
|
57 | var val
|
58 |
|
59 | req.originalMethod = req.originalMethod || req.method
|
60 |
|
61 |
|
62 | if (methods && methods.indexOf(req.originalMethod) === -1) {
|
63 | return next()
|
64 | }
|
65 |
|
66 | val = get(req, res)
|
67 | method = Array.isArray(val)
|
68 | ? val[0]
|
69 | : val
|
70 |
|
71 | // replace
|
72 | if (method !== undefined && supports(method)) {
|
73 | req.method = method.toUpperCase()
|
74 | debug('override %s as %s', req.originalMethod, req.method)
|
75 | }
|
76 |
|
77 | next()
|
78 | }
|
79 | }
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | function createGetter(str) {
|
86 | if (str.substr(0, 2).toUpperCase() === 'X-') {
|
87 |
|
88 | return createHeaderGetter(str)
|
89 | }
|
90 |
|
91 | return createQueryGetter(str)
|
92 | }
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | function createQueryGetter(key) {
|
99 | return function(req, res) {
|
100 | var url = parseurl(req)
|
101 | var query = querystring.parse(url.query || '')
|
102 | return query[key]
|
103 | }
|
104 | }
|
105 |
|
106 |
|
107 |
|
108 |
|
109 |
|
110 | function createHeaderGetter(str) {
|
111 | var header = str.toLowerCase()
|
112 |
|
113 | return function(req, res) {
|
114 |
|
115 | vary(res, str)
|
116 |
|
117 |
|
118 | return (req.headers[header] || '').split(/ *, */)
|
119 | }
|
120 | }
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 | function supports(method) {
|
127 | return method
|
128 | && typeof method === 'string'
|
129 | && methods.indexOf(method.toLowerCase()) !== -1
|
130 | }
|