Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,22 @@ npm install koa-methodoverride
var app = require('koa')();
var methodOverride = require('koa-methodoverride');

app.use(methodOverride());
app.use(methodOverride('_method'));

app.listen(3000);
```

This package leverages [async-busboy](https://github.com/m4nuC/async-busboy) for `multipart/formdata` enctype.
For those who want to read files and fields in this case, a new helper method `ctx.req.getAsyncBusboyBody()` is exposed.
Thus, instead of
```js
const { files, fields } = await asyncBusboy(ctx.req);
```
, you need to use
```js
const { files, fields } = await ctx.req.getAsyncBusboyBody();
```


### License

Expand Down
31 changes: 22 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@

const debug = require('debug')('method-override')
const methods = require('methods')
const asyncBusboy = require('async-busboy')

const ALLOWED_METHODS = 'POST'
const HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override"

let asyncBusboyBody = null

/**
* Method Override:
*
Expand Down Expand Up @@ -57,7 +60,7 @@ function methodOverride(getter, options) {
? ALLOWED_METHODS.split(' ')
: options.methods

return (ctx, next) => {
return async (ctx, next) => {
const req = ctx.request
let method
let val
Expand All @@ -69,7 +72,10 @@ function methodOverride(getter, options) {
return next()
}

val = get(req, ctx.response)
asyncBusboyBody = null
ctx.req.getAsyncBusboyBody = async () => (asyncBusboyBody || await asyncBusboy(ctx.req))

val = await get(req, ctx.response, ctx.req)
method = Array.isArray(val) ? val[0] : val

// replace
Expand All @@ -92,18 +98,25 @@ function createGetter(str) {
return createHeaderGetter(str)
}

return createQueryGetter(str)
return createQueryOrBodyGetter(str)
}

/**
* Create a getter for the given query key name.
* Create a getter for the given query or body key name.
*/

function createQueryGetter(key) {
return queryGetter

function queryGetter(req) {
return req.query[key]
function createQueryOrBodyGetter(key) {
return queryOrBodyGetter

async function queryOrBodyGetter(req, ...args) {
const method = req.query[key] || (req.body && req.body[key])
if (method) {
return method
} else {
const koaReq = args[1]
asyncBusboyBody = await asyncBusboy(koaReq)
return asyncBusboyBody.fields[key]
}
}
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"middleware"
],
"dependencies": {
"async-busboy": "^0.3.3",
"debug": "*",
"methods": "*"
},
Expand Down