Files
patriothacks/api/blob/index.ts
T

25 lines
898 B
TypeScript

import type { IncomingMessage, ServerResponse } from "node:http";
import { BlobTooLargeError, MAX_BLOB_SIZE_BYTES, putBlob } from "../_lib/blobStore.ts";
import { readLimitedBody, sendJson } from "../_lib/httpUtils.ts";
export default async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== "POST") {
sendJson(res, 405, { error: "method not allowed, use POST" });
return;
}
const contentType = req.headers["content-type"] ?? "application/octet-stream";
try {
const body = await readLimitedBody(req, MAX_BLOB_SIZE_BYTES);
const { id } = await putBlob(body, contentType);
sendJson(res, 201, { id });
} catch (err) {
if (err instanceof BlobTooLargeError) {
sendJson(res, 413, { error: err.message, maxBytes: err.limitBytes });
return;
}
sendJson(res, 500, { error: "failed to store blob" });
}
}