This commit is contained in:
Rizky 2024-06-28 00:15:23 +07:00
parent 5e90332489
commit 904585868a
2 changed files with 20 additions and 12 deletions

View File

@ -54,7 +54,7 @@ export const createResponse = (
cache_accept?: string; cache_accept?: string;
headers?: any; headers?: any;
res?: any; res?: any;
br?: boolean; high_compression?: boolean;
} }
) => { ) => {
const status = const status =
@ -64,7 +64,10 @@ export const createResponse = (
const headers = { ...(opt?.headers || {}) } as Record<string, string>; const headers = { ...(opt?.headers || {}) } as Record<string, string>;
if (opt?.cache_accept) { if (opt?.cache_accept) {
let cached = false; let cached = false;
if (opt?.br && opt.cache_accept.toLowerCase().includes("br")) { if (
opt?.high_compression &&
opt.cache_accept.toLowerCase().includes("br")
) {
const content_hash = simpleHash(content); const content_hash = simpleHash(content);
if (!g.cache.br[content_hash]) { if (!g.cache.br[content_hash]) {
@ -78,18 +81,23 @@ export const createResponse = (
} }
} }
if (!cached && opt.cache_accept.toLowerCase().includes("gz")) { if (opt?.high_compression) {
const content_hash = simpleHash(content); if (!cached && opt.cache_accept.toLowerCase().includes("gz")) {
const content_hash = simpleHash(content);
if (!g.cache.gz[content_hash]) { if (!g.cache.gz[content_hash]) {
g.cache.gz[content_hash] = Bun.gzipSync(content); g.cache.gz[content_hash] = Bun.gzipSync(content);
} }
if (g.cache.gz[content_hash]) { if (g.cache.gz[content_hash]) {
cached = true; cached = true;
content = g.cache.gz[content_hash]; content = g.cache.gz[content_hash];
headers["content-encoding"] = "gzip"; headers["content-encoding"] = "gzip";
}
} }
} else {
content = Bun.gzipSync(content);
headers["content-encoding"] = "gzip";
} }
} }

View File

@ -9,7 +9,7 @@ export const serveWeb = async (arg: {
const type = mime.getType(arg.pathname); const type = mime.getType(arg.pathname);
return createResponse(arg.content, { return createResponse(arg.content, {
cache_accept: arg.cache_accept, cache_accept: arg.cache_accept,
br: true, high_compression: true,
headers: !type ? undefined : { "content-type": type }, headers: !type ? undefined : { "content-type": type },
}); });
}; };