47 lines
1.7 KiB
JavaScript
47 lines
1.7 KiB
JavaScript
export function sendJson(response, status, payload, headers = {}) {
|
|
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...headers });
|
|
response.end(JSON.stringify(payload));
|
|
}
|
|
|
|
export function sendError(response, status, message, details) {
|
|
sendJson(response, status, { ok: false, message, ...(details ? { details } : {}) });
|
|
}
|
|
|
|
export async function readJson(request) {
|
|
const chunks = [];
|
|
let size = 0;
|
|
for await (const chunk of request) {
|
|
size += chunk.length;
|
|
if (size > 1024 * 1024) throw Object.assign(new Error('请求内容过大'), { status: 413 });
|
|
chunks.push(chunk);
|
|
}
|
|
if (!chunks.length) return {};
|
|
try {
|
|
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
} catch {
|
|
throw Object.assign(new Error('请求数据格式不正确'), { status: 400 });
|
|
}
|
|
}
|
|
|
|
export async function readBodyBuffer(request, maxBytes = 12 * 1024 * 1024) {
|
|
const chunks = [];
|
|
let size = 0;
|
|
for await (const chunk of request) {
|
|
size += chunk.length;
|
|
if (size > maxBytes) throw Object.assign(new Error('Excel 文件不能超过 12 MB'), { status: 413 });
|
|
chunks.push(chunk);
|
|
}
|
|
if (!chunks.length) throw Object.assign(new Error('请选择要导入的 Excel 文件'), { status: 400 });
|
|
return Buffer.concat(chunks);
|
|
}
|
|
|
|
export function sendWorkbook(response, buffer, filename) {
|
|
response.writeHead(200, {
|
|
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
|
|
'Content-Length': buffer.length,
|
|
'Cache-Control': 'no-store'
|
|
});
|
|
response.end(buffer);
|
|
}
|