UNPKG

cf-workers-query

Version:

Automatically cache and revalidate data in Cloudflare Workers. Using the Cache API and Execution Context

53 lines (50 loc) 1.3 kB
import { __name, createQuery } from "../chunk-KU66F4VA.js"; // node_modules/hono/dist/http-exception.js var HTTPException = class extends Error { static { __name(this, "HTTPException"); } res; status; constructor(status = 500, options) { super(options?.message, { cause: options?.cause }); this.res = options?.res; this.status = status; } getResponse() { if (this.res) { const newResponse = new Response(this.res.body, { status: this.status, headers: this.res.headers }); return newResponse; } return new Response(this.message, { status: this.status }); } }; // src/lib/hono.ts var cache = /* @__PURE__ */ __name(({ cacheKey, handler, revalidate, ...options }) => async (ctx, next) => { const { data: response, error } = await createQuery({ ...options, queryKey: typeof cacheKey === "function" ? cacheKey(ctx) : cacheKey, queryFn: /* @__PURE__ */ __name(() => handler(ctx, next), "queryFn"), throwOnError: true, ...revalidate ? { revalidate: typeof revalidate === "boolean" ? revalidate : revalidate(ctx) } : {} }); if (!response || error) { throw new HTTPException(500); } return new Response(response.body, response); }, "cache"); export { cache };