first
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
import * as errors from '../custom-errors';
|
||||
|
||||
export const bodyParser: () => MiddlewareHandler = () => async (ctx, next) => {
|
||||
if (!['POST', 'PUT', 'PATCH'].includes(ctx.req.method.toUpperCase())) {
|
||||
ctx.set('body', {});
|
||||
return next();
|
||||
}
|
||||
|
||||
const contentType = ctx.req.header('Content-Type') || '';
|
||||
|
||||
try {
|
||||
if (contentType.includes('application/json')) {
|
||||
const text = await ctx.req.text();
|
||||
const body = text ? JSON.parse(text) : {};
|
||||
ctx.set('body', body);
|
||||
} else if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const body = await ctx.req.parseBody();
|
||||
ctx.set('body', body);
|
||||
} else if (contentType.includes('multipart/form-data')) {
|
||||
const body = await ctx.req.parseBody({ all: true });
|
||||
ctx.set('body', body);
|
||||
} else {
|
||||
// No recognized content type, set empty body
|
||||
ctx.set('body', {});
|
||||
}
|
||||
} catch (ex) {
|
||||
// throw errors.BAD_REQUEST('Invalid request body');
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
Reference in New Issue
Block a user