Skip to content

Commit

Permalink
allow JSON in multipart bodies
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewplummer committed May 24, 2024
1 parent f588cf1 commit 514f870
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions services/api/src/utils/middleware/body.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
const compose = require('koa-compose');
const { koaBody } = require('koa-body');

module.exports = function () {
const unparsed = Symbol.for('unparsedBody');

function composeMiddlewares() {
return compose([
koaBody({
multipart: true,
includeUnparsed: true,
}),
includeRawBody(),
parseMultipartBody(),
]);
};
}

// Allow koa body to parse the body first, then pull
// out a reference to the raw body and add it to request
// as it may be lost if other middleware (such as validate)
// overwrite the body.
function includeRawBody() {
return async (ctx, next) => {
ctx.request.rawBody = ctx.request.body[unparsed];
return next();
};
}

// Multipart bodies are assumed to be simple key/value pairs.
// This middleware parses each field as JSON to allow the client
Expand All @@ -23,3 +38,5 @@ function parseMultipartBody() {
return next();
};
}

module.exports = composeMiddlewares;

0 comments on commit 514f870

Please sign in to comment.