@busy-hour/blaze
Version:
<h1 align='center'>🔥 Blaze</h1> <div align='center'> An event driven framework for 🔥 Hono.js </div>
71 lines (70 loc) • 1.96 kB
JavaScript
// src/middlewares/body-limit.ts
import { handleRest } from "../handler/rest.js";
import { BlazeContext } from "../internal/context/index.js";
import { BlazeError } from "../internal/errors/index.js";
function errorHandler(onError) {
return async function errorHandler2(honoCtx) {
const ctx = new BlazeContext({
body: null,
honoCtx,
headers: null,
meta: null,
params: null,
query: null
});
const rest = await handleRest({
ctx,
honoCtx,
promise: onError(ctx)
});
return rest.resp;
};
}
function bodyLimit(options) {
const handler = options.onError ?? // deno-lint-ignore require-await
(async () => {
throw new BlazeError("Payload too large", 413);
});
const onError = errorHandler(handler);
return async function bodyLimit2(honoCtx, next) {
if (!honoCtx.req.raw.body) {
return next();
}
if (honoCtx.req.raw.headers.has("content-length")) {
const contentLength = parseInt(
honoCtx.req.raw.headers.get("content-length") || "0",
10
);
return contentLength > options.maxSize ? onError(honoCtx) : next();
}
let size = 0;
const rawReader = honoCtx.req.raw.body.getReader();
const reader = new ReadableStream({
async start(controller) {
try {
for (; ; ) {
const { done, value } = await rawReader.read();
if (done)
break;
size += value.length;
if (size > options.maxSize) {
controller.error(new BlazeError("Request too large", 413));
break;
}
controller.enqueue(value);
}
} finally {
controller.close();
}
}
});
honoCtx.req.raw = new Request(honoCtx.req.raw, { body: reader });
await next();
if (honoCtx.error instanceof BlazeError) {
honoCtx.res = await onError(honoCtx);
}
};
}
export {
bodyLimit
};