Skip to content

Commit

Permalink
Cache syntax highlighting for 30 days
Browse files Browse the repository at this point in the history
  • Loading branch information
zephraph committed Oct 6, 2024
1 parent 30784bd commit 8ab2642
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/astro-md/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { myRemark } from "../my-remark";
import { remarkObsidian } from "../remark-obsidian";
import remarkFrontmatter from "remark-frontmatter";

// Cache for 30 days
const syntaxHighlightCacheTtl = 60 * 60 * 24 * 30;

const decode = (str: string) =>
str.replace(/&#x(\w+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));

Expand Down Expand Up @@ -37,11 +40,17 @@ class SyntaxHighlightRewriter implements HTMLRewriterElementContentHandlers {
.map((b) => b.toString(16).padStart(2, "0"))
.join("");

const cachedResult = await this.cache.get(hash);
const cachedResult = await this.cache.get(hash, {
cacheTtl: syntaxHighlightCacheTtl,
});
if (cachedResult) {
text.replace(cachedResult, { html: true });
return;
}
// When setting cacheTtl, even misses are cached. If we've gotten
// to this point the cache is empty, so let's clear the miss so that
// the next request has the actual content (after we write it)
this.runtime.ctx.waitUntil(this.cache.get(hash));

const res = await fetch(
`https://highlight.val.just-be.dev?lang=${this.lang}&theme=${theme}`,
Expand Down

0 comments on commit 8ab2642

Please sign in to comment.