push
This commit is contained in:
1 parent
bcf05e8063
commit
f37985b4c8
109 files changed
+22810
-6143
No files matched your search
+65
@@ -0,0 +1,65 @@
|
||||
const zlib = require('zlib');
|
||||
|
||||
const CORS = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Expose-Headers': 'Content-Length, Content-Range, Accept-Ranges, X-Bug-Tv-Offset',
|
||||
};
|
||||
|
||||
// compress text bodies only; media is already compressed
|
||||
function send(req, res, status, body, type, extra = {}) {
|
||||
const buf = Buffer.isBuffer(body) ? body : Buffer.from(String(body));
|
||||
const headers = { ...CORS, 'Content-Type': type, 'Cache-Control': 'no-store', Vary: 'Accept-Encoding', ...extra };
|
||||
const accept = String(req.headers['accept-encoding'] || '');
|
||||
if (buf.length > 1024 && /\bbr\b/.test(accept)) {
|
||||
const out = zlib.brotliCompressSync(buf, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 } });
|
||||
res.writeHead(status, { ...headers, 'Content-Encoding': 'br', 'Content-Length': out.length });
|
||||
return res.end(out);
|
||||
}
|
||||
if (buf.length > 1024 && /\bgzip\b/.test(accept)) {
|
||||
const out = zlib.gzipSync(buf, { level: 5 });
|
||||
res.writeHead(status, { ...headers, 'Content-Encoding': 'gzip', 'Content-Length': out.length });
|
||||
return res.end(out);
|
||||
}
|
||||
res.writeHead(status, { ...headers, 'Content-Length': buf.length });
|
||||
res.end(buf);
|
||||
}
|
||||
|
||||
function json(req, res, status, obj, extra) {
|
||||
return send(req, res, status, JSON.stringify(obj), 'application/json; charset=utf-8', extra);
|
||||
}
|
||||
|
||||
function error(req, res, status, message, extra = {}) {
|
||||
return json(req, res, status, { error: message, ...extra });
|
||||
}
|
||||
|
||||
// Server-sent events; returns { event(name, data), close() }.
|
||||
function sse(req, res) {
|
||||
res.writeHead(200, {
|
||||
...CORS,
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
});
|
||||
res.flushHeaders?.();
|
||||
const ping = setInterval(() => res.write(': ping\n\n'), 15000);
|
||||
let closed = false;
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(ping);
|
||||
res.end();
|
||||
};
|
||||
req.on('close', close);
|
||||
return {
|
||||
event(name, data) {
|
||||
if (!closed) res.write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
},
|
||||
close,
|
||||
get closed() {
|
||||
return closed;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { CORS, send, json, error, sse };
|
||||
Reference in new issue
Block a user