Last active
October 7, 2019 12:32
-
-
Save fl0w/48da06b652692f09ad16288a735ed9b6 to your computer and use it in GitHub Desktop.
Simple for-await JSON body parser for Koa (node.js)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { StringDecoder } = require('string_decoder') | |
const decoder = new StringDecoder() // default utf8 | |
// Note that this is a naive example | |
// There's no safe-guarding and the process could be flooded easily b/c there's no limits. | |
// This is just to illustrate how to use for-await in Koa | |
async function bodyParser (ctx, next) { | |
let acc = '' | |
for await (const chunk of ctx.req) acc += decode.write(chunk) | |
ctx.state.body = JSON.parse(acc) | |
await next() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage, simple Koa application | |
const Koa = require('koa') | |
const app = new Koa() | |
app.use(bodyParser) | |
app.use(async (ctx) => { | |
ctx.body = ctx.state.body | |
}) | |
app.listen(8000) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage, simple Koa application | |
const Koa = require('koa') | |
const Router = require('@koa/router') | |
const app = new Koa() | |
const r = new Router() | |
r.post('/', bodyParser, async (ctx) => { | |
ctx.body = ctx.state.body | |
}) | |
app | |
.use(r.routes()) | |
.use(r.allowedMethods()) | |
.listen(8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment