Skip to content

Instantly share code, notes, and snippets.

@fl0w

fl0w/bodyparser.js

Last active Oct 7, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.