Skip to content

Commit f0f09cf

Browse files
committed
fix: allow configurable method override
1 parent 8d360d7 commit f0f09cf

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

index.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,20 @@ class Web {
102102
return cryptoRandomString({ length: 32 });
103103
},
104104

105+
methodOverride: [
106+
req => {
107+
const { _method } = req.body;
108+
if (
109+
typeof _method !== 'string' &&
110+
!['PUT', 'DELETE'].includes(_method)
111+
) {
112+
throw new Error(`method override of ${_method} is not valid`);
113+
}
114+
115+
return _method;
116+
}
117+
],
118+
105119
helmet: {
106120
contentSecurityPolicy: defaultSrc
107121
? {
@@ -298,16 +312,17 @@ class Web {
298312
// flash messages
299313
app.use(flash());
300314

301-
// method override
302-
// (e.g. `<input type="hidden" name="_method" value="PUT" />`)
303-
app.use(methodOverride());
304-
305315
// body parser
306316
app.use(bodyParser());
307317

308318
// pretty-printed json responses
309319
app.use(json());
310320

321+
// method override
322+
// (e.g. `<input type="hidden" name="_method" value="PUT" />`)
323+
if (this.config.methodOverride)
324+
app.use(methodOverride(...this.config.methodOverride));
325+
311326
// ajax request detection (sets `ctx.state.xhr` boolean)
312327
app.use(isajax());
313328

test/test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,27 @@ test('allows custom routes', async t => {
1818
t.is(res.status, 200);
1919
t.is(res.body.ok, 'ok');
2020
});
21+
22+
test('default method override', async t => {
23+
const router = new Router();
24+
25+
router.post('/', ctx => {
26+
ctx.body = { method: 'post' };
27+
});
28+
29+
router.put('/', ctx => {
30+
ctx.body = { method: 'put' };
31+
});
32+
33+
const web = new Web({
34+
routes: router.routes()
35+
});
36+
37+
const res = await request(web.server)
38+
.post('/')
39+
.send({ _method: 'PUT' })
40+
.set('Accept', 'application/json');
41+
t.is(res.status, 200);
42+
t.is(res.body.method, 'put');
43+
t.is(res.request.method, 'POST');
44+
});

0 commit comments

Comments
 (0)