diff --git a/Parser.js b/Parser.js new file mode 100644 index 0000000..07ccc46 --- /dev/null +++ b/Parser.js @@ -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() +} \ No newline at end of file diff --git a/README.md b/README.md index 122319e..25afd13 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,39 @@ -# koa-parser -Koa Body Parser Middleware +# Koa Body Parser +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" +``` diff --git a/package.json b/package.json new file mode 100644 index 0000000..f7b7993 --- /dev/null +++ b/package.json @@ -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" +} \ No newline at end of file