koa-etag
Version:
Koa ETag support middleware
32 lines (31 loc) • 926 B
JavaScript
// src/index.ts
import Stream from "stream";
import { Buffer } from "buffer";
import fs from "fs/promises";
import calculate from "etag";
async function getResponseEntity(ctx) {
const body = ctx.body;
if (!body || ctx.response.get("etag")) return;
const status = Math.trunc(ctx.status / 100);
if (status !== 2) return;
if (body instanceof Stream) {
if (!("path" in body) || typeof body.path !== "string") return;
return fs.stat(body.path);
}
if (typeof body === "string" || Buffer.isBuffer(body)) return body;
return JSON.stringify(body);
}
function etag(options) {
console.warn(
"[DEPRECATION WARNING] This package will be deprecated. Please use @koa/etag (v5+) instead."
);
return async function(ctx, next) {
await next();
const entity = await getResponseEntity(ctx);
if (!entity) return;
ctx.response.etag = calculate(entity, options);
};
}
export {
etag as default
};