UNPKG

1.52 kBJavaScriptView Raw
1import { createError } from '@middy/util';
2import parse from 'qs/lib/parse.js';
3const mimePattern = /^application\/x-www-form-urlencoded(;.*)?$/;
4const defaults = {
5 disableContentTypeError: false
6};
7const httpUrlencodeBodyParserMiddleware = (opts = {})=>{
8 const options = {
9 ...defaults,
10 ...opts
11 };
12 const httpUrlencodeBodyParserMiddlewareBefore = async (request)=>{
13 const { headers, body } = request.event;
14 const contentType = headers?.['Content-Type'] ?? headers?.['content-type'];
15 if (!mimePattern.test(contentType)) {
16 if (options.disableContentTypeError) {
17 return;
18 }
19 throw createError(415, 'Unsupported Media Type', {
20 cause: {
21 package: '@middy/http-urlencode-body-parser',
22 data: contentType
23 }
24 });
25 }
26 const data = request.event.isBase64Encoded ? Buffer.from(body, 'base64').toString() : body;
27 const rawBody = body;
28 request.event.body = parse(data);
29 if (request.event.body?.[rawBody] === '') {
30 // UnprocessableEntity
31 throw createError(415, 'Invalid or malformed URL encoded form was provided', {
32 cause: {
33 package: '@middy/http-urlencode-body-parser'
34 }
35 });
36 }
37 };
38 return {
39 before: httpUrlencodeBodyParserMiddlewareBefore
40 };
41};
42export default httpUrlencodeBodyParserMiddleware;
43