strong-tie/inbound-calls
0
1'use strict'2 3const { test } = require('node:test')4const sget = require('simple-get').concat5const Fastify = require('..')6const { getServerUrl } = require('./helper')7 8process.removeAllListeners('warning')9 10test('Wrong parseAs parameter', t => {11 t.plan(2)12 const fastify = Fastify()13 14 try {15 fastify.addContentTypeParser('application/json', { parseAs: 'fireworks' }, () => {})16 t.assert.fail('should throw')17 } catch (err) {18 t.assert.strictEqual(err.code, 'FST_ERR_CTP_INVALID_PARSE_TYPE')19 t.assert.strictEqual(err.message, "The body parser can only parse your data as 'string' or 'buffer', you asked 'fireworks' which is not supported.")20 }21})22 23test('Should allow defining the bodyLimit per parser', (t, done) => {24 t.plan(3)25 const fastify = Fastify()26 t.after(() => fastify.close())27 28 fastify.post('/', (req, reply) => {29 reply.send(req.body)30 })31 32 fastify.addContentTypeParser(33 'x/foo',34 { parseAs: 'string', bodyLimit: 5 },35 function (req, body, done) {36 t.assert.fail('should not be invoked')37 done()38 }39 )40 41 fastify.listen({ port: 0 }, err => {42 t.assert.ifError(err)43 44 sget({45 method: 'POST',46 url: getServerUrl(fastify),47 body: '1234567890',48 headers: {49 'Content-Type': 'x/foo'50 }51 }, (err, response, body) => {52 t.assert.ifError(err)53 t.assert.deepStrictEqual(JSON.parse(body.toString()), {54 statusCode: 413,55 code: 'FST_ERR_CTP_BODY_TOO_LARGE',56 error: 'Payload Too Large',57 message: 'Request body is too large'58 })59 done()60 })61 })62})63 64test('route bodyLimit should take precedence over a custom parser bodyLimit', (t, done) => {65 t.plan(3)66 const fastify = Fastify()67 t.after(() => fastify.close())68 69 fastify.post('/', { bodyLimit: 5 }, (request, reply) => {70 reply.send(request.body)71 })72 73 fastify.addContentTypeParser(74 'x/foo',75 { parseAs: 'string', bodyLimit: 100 },76 function (req, body, done) {77 t.assert.fail('should not be invoked')78 done()79 }80 )81 82 fastify.listen({ port: 0 }, err => {83 t.assert.ifError(err)84 85 sget({86 method: 'POST',87 url: getServerUrl(fastify),88 body: '1234567890',89 headers: { 'Content-Type': 'x/foo' }90 }, (err, response, body) => {91 t.assert.ifError(err)92 t.assert.deepStrictEqual(JSON.parse(body.toString()), {93 statusCode: 413,94 code: 'FST_ERR_CTP_BODY_TOO_LARGE',95 error: 'Payload Too Large',96 message: 'Request body is too large'97 })98 done()99 })100 })101})102 