Skip to content

Instantly share code, notes, and snippets.

@fl0w
Last active October 7, 2019 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fl0w/48da06b652692f09ad16288a735ed9b6 to your computer and use it in GitHub Desktop.
Save fl0w/48da06b652692f09ad16288a735ed9b6 to your computer and use it in GitHub Desktop.
Simple for-await JSON body parser for Koa (node.js)
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()
}
// 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)
// 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