Skip to main content
Module

x/parsec/README.md

๐ŸŒŒ Tiny body parser for Deno. Port of the milliparsec library.
Go to Latest
File

parsec ๐ŸŒŒ

nest badge GitHub release (latest by date) GitHub Workflow Status Codecov

Tiny body parser for Deno. Port of the milliparsec library.

Features

  • supports JSON and urlencoded body parsing
  • parses only when Content-Type header matches the parserโ€™s type
  • custom callback function

Examples

Vanilla

import { serve } from 'https://deno.land/std@0.89.0/http/server.ts'
import { json, ReqWithBody } from 'https://deno.land/x/parsec/mod.ts'

const s = serve({ port: 3000 })

for await (const req of s) {
  await json(req, undefined, (err) => {
    if (err) req.respond({ status: 400, body: err.message })
    else req.respond({ status: 204 })
  })
  if (!(req as ReqWithBody).requestBody) {
    req.respond({ status: 404, body: 'No body found' })
  } else {
    const response = JSON.stringify((req as ReqWithBody).requestBody, null, 2)
    req.respond({ body: response })
  }
}

tinyhttp

import { App, Request } from 'https://deno.land/x/tinyhttp/mod.ts'
import { json, ReqWithBody } from 'https://deno.land/x/parsec/mod.ts'

const app = new App<unknown, Request & ReqWithBody>()

app
  .use(json)
  .post((req, res) => {
    res.send(req.requestBody || {})
  })
  .listen(3000, () => console.log(`Started on :3000`))

Opine

import { opine } from 'https://deno.land/x/opine/mod.ts'
import { json } from 'https://deno.land/x/parsec/mod.ts'

const app = opine()

app
  .use(json)
  .post('/', (req, res) => {
    res.send(req.parsedBody || {})
  })
  .listen(3000, () => console.log(`Started on :3000`))

Oak

import { Application } from 'https://deno.land/x/oak/mod.ts'
import { json, ReqWithBody } from 'https://deno.land/x/parsec/mod.ts'

const app = new Application()

app
  .use((ctx, next) => json(ctx.request.serverRequest, undefined, next))
  .use((ctx) => {
    if (ctx.request.method === 'POST') {
      ctx.response.body = (ctx.request.serverRequest as ReqWithBody).parsedBody
    }
  })

await app.listen({ port: 3000 })

Then run:

curl -X POST localhost:3000 -d '{ "abc": "def" }' -H "Content-Type: application/json"