Readme Doc

This commit is contained in:
nicco 2017-08-18 19:16:14 +02:00
parent 14f878fd64
commit e70398f9c1
3 changed files with 115 additions and 2 deletions

53
Parser.js Normal file
View File

@ -0,0 +1,53 @@
const TYPES = {
'multipart/form-data': (b) => {
let bObj = {}
b = b.split('\r\n')
const n = Math.floor(b.length / 4)
for (let i = 0; i < n; i++) {
const
tmp = i * 4,
key = b[tmp + 1].split(';')[1].split('=')[1].slice(1, -1),
value = b[tmp + 3]
bObj[key] = value
}
return bObj
},
'application/x-www-form-urlencoded': (b) => {
let bObj = {}
b.split('&').forEach(v => {
const tmp = v.split('=')
bObj[unescape(tmp[0])] = unescape(tmp[1])
})
return bObj
},
'application/json': (b) => {
return JSON.parse(b)
},
}
module.exports = async(c, n) => {
await new Promise((res) => {
let bodyStr = ''
c.req.on('data', (chunk) => {
bodyStr += chunk.toString()
})
c.req.on('end', () => {
let bodyObj = {}
if (c.request.header['content-type'] !== undefined) {
const curType = c.request.header['content-type'].split(';')[0]
for (const i in TYPES)
if (curType === i)
try {
bodyObj = TYPES[i](bodyStr)
} catch (e) {
bodyObj = {}
}
}
c.request.body = bodyObj
res()
})
})
await n()
}

View File

@ -1,2 +1,39 @@
# koa-parser # Koa Body Parser
Koa Body Parser Middleware Koa-Middleware for parsing body parameters in the request. Lightweight and no dependencies.
##### Supported encodings:
- form-data
- x-www-form-urlencoded
- json
### Complete Example
```javascript
const
Koa = require('koa'),
router = require('koa-simple-router'),
parser = require('cca-koa-parser')
const
app = new Koa(),
port = 3001
app.use(parser)
app.use(router({}, _ => {
_.post('/', (c, n) => {
c.body = [200, c.request.body]
})
}))
app.listen(port)
```
## Documentation
##### ~ `body` Element
The Parser defines an object `ctx.request.body` where all the sent parameters are stored
###### Example
```javascript
// Request: HTTP POST /
ctx.request.body['username'] => "joe"
```

23
package.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "cca-koa-parser",
"version": "0.1.0",
"description": "Koa Body Parser",
"main": "Parser.js",
"repository": {
"type": "git",
"url": "git+https://github.com/CupCakeArmy/koa-parser.git"
},
"keywords": [
"Koa",
"Middleware",
"Body",
"Parser",
"Lightweight"
],
"author": "Niccolo Borgioli",
"license": "ISC",
"bugs": {
"url": "https://github.com/CupCakeArmy/koa-parser/issues"
},
"homepage": "https://github.com/CupCakeArmy/koa-parser#readme"
}