CoolFace
Apppublic

strong-tie/inbound-calls

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
parser.js54 linesDownload Raw Back to examples
1'use strict'2 3const fastify = require('../fastify')({ logger: true })4const jsonParser = require('fast-json-body')5const querystring = require('node:querystring')6 7// Handled by fastify8// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/9 10// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/jsoff' http://localhost:3000/11fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {12  jsonParser(payload, function (err, body) {13    done(err, body)14  })15})16 17// curl -X POST -d 'hello=world' -H'Content-type: application/x-www-form-urlencoded' http://localhost:3000/18fastify.addContentTypeParser('application/x-www-form-urlencoded', function (request, payload, done) {19  let body = ''20  payload.on('data', function (data) {21    body += data22  })23  payload.on('end', function () {24    try {25      const parsed = querystring.parse(body)26      done(null, parsed)27    } catch (e) {28      done(e)29    }30  })31  payload.on('error', done)32})33 34// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/vnd.custom+json' http://localhost:3000/35fastify.addContentTypeParser(/^application\/.+\+json$/, { parseAs: 'string' }, fastify.getDefaultJsonParser('error', 'ignore'))36 37// remove default json parser38// curl -X POST -d '{"hello":"world"}' -H'Content-type: application/json' http://localhost:3000/ is now no longer handled by fastify39fastify.removeContentTypeParser('application/json')40 41// This call would remove any content type parser42// fastify.removeAllContentTypeParsers()43 44fastify45  .post('/', function (req, reply) {46    reply.send(req.body)47  })48 49fastify.listen({ port: 3000 }, err => {50  if (err) {51    throw err52  }53})54