cache example
parent
5486079888
commit
bbf3c6f57d
@ -1,16 +1,52 @@
|
|||||||
import Elysia from "elysia";
|
import Elysia from "elysia";
|
||||||
import { BaseHtml } from "../components/base";
|
import { BaseHtml } from "../components/base";
|
||||||
import { ctx } from "../context";
|
import { ctx } from "../context";
|
||||||
|
import { renderToString } from "beth-jsx";
|
||||||
|
import { persistedCache, revalidateTag } from "../beth/cache";
|
||||||
|
|
||||||
export const index = new Elysia().use(ctx).get("/", ({ html }) =>
|
const start = Date.now();
|
||||||
html(
|
|
||||||
<BaseHtml>
|
const getTime = async () => (Date.now() - start) / 1000;
|
||||||
<div
|
|
||||||
class="flex w-full h-screen justify-center items-center"
|
const cachedGetTime = persistedCache(getTime, "getTime", {
|
||||||
hx-get="/api/todos"
|
tags: ["time"],
|
||||||
hx-swap="innerHTML"
|
revalidate: 2,
|
||||||
hx-trigger="load"
|
});
|
||||||
/>
|
|
||||||
</BaseHtml>
|
export const index = new Elysia()
|
||||||
)
|
.use(ctx)
|
||||||
);
|
.onRequest(({ request }) => {
|
||||||
|
const revalidate = request.headers.get("HX-Revalidate");
|
||||||
|
if (revalidate) {
|
||||||
|
const tags = JSON.parse(revalidate);
|
||||||
|
tags.forEach((tag: string) => {
|
||||||
|
revalidateTag(tag);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.get("/test", async () => {
|
||||||
|
const time = await cachedGetTime();
|
||||||
|
return renderToString(() => <p safe>{time}</p>);
|
||||||
|
})
|
||||||
|
.get("/", async ({ set }) => {
|
||||||
|
set.headers["content-type"] = "text/html";
|
||||||
|
return renderToString(() => (
|
||||||
|
<BaseHtml>
|
||||||
|
<h1>cache revalidates on two second interval</h1>
|
||||||
|
<button hx-get="/test" hx-target="#foo" hx-swap="beforeend">
|
||||||
|
click me to get time (cached)
|
||||||
|
</button>
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
<button
|
||||||
|
hx-get="/test"
|
||||||
|
hx-target="#foo"
|
||||||
|
hx-swap="beforeend"
|
||||||
|
hx-revalidate="time"
|
||||||
|
>
|
||||||
|
click me (revalidate now)
|
||||||
|
</button>
|
||||||
|
<div id="foo"></div>
|
||||||
|
</BaseHtml>
|
||||||
|
));
|
||||||
|
});
|
||||||
|
Loading…
Reference in New Issue