添加博客渲染缓存

This commit is contained in:
2026-04-07 12:57:47 +08:00
parent ca1cf10aa8
commit 1b8bd19370
4 changed files with 69 additions and 8 deletions

16
src/lib/markdoc-cache.ts Normal file
View File

@ -0,0 +1,16 @@
import type { RenderableTreeNode } from '@markdoc/markdoc'
import KeyV from 'keyv'
import { createHash } from 'node:crypto'
const markdocVersion = '1'
export const markdocCache = new KeyV<RenderableTreeNode>({
namespace: `markdoc-cache-${markdocVersion}`,
ttl: 1000 * 60 * 60 * 24 * 7,
})
export const generateCacheKey = (content: string) => {
return createHash('sha256')
.update(content)
.update(markdocVersion)
.digest('hex')
}

View File

@ -12,6 +12,15 @@ export const markdocConfig: Config = {
highlightedHtml: { type: String },
},
transform(node, config) {
/*
* 注意力!!!!!!!!!!!!!!
* 注意!!!!!!!!!!!!
*
* 如果改了这里的逻辑,记得更改 `markdoc-cache.ts` 里的版本号
* 以让对应的缓存能够被更新
*
**/
const attributes = node.transformAttributes(config)
const highlightedHtml = shikiRender(
@ -29,8 +38,28 @@ export const markdocConfig: Config = {
},
}
export const toMarkdocTree = async (content: string) => {
const _toMarkdocTree = async (content: string) => {
const ast = Markdoc.parse(content)
await ensureShikiEngine()
return Markdoc.transform(ast, markdocConfig)
const tree = Markdoc.transform(ast, markdocConfig)
return tree
}
export const toMarkdocTree = async (content: string) => {
if (!import.meta.env.SSR) {
return await _toMarkdocTree(content)
}
const cacheLib = await import('./markdoc-cache.ts')
const key = cacheLib.generateCacheKey(content)
const cached = await cacheLib.markdocCache.get(key)
if (cached) {
return cached
}
const tree = await _toMarkdocTree(content)
cacheLib.markdocCache.set(key, tree)
return tree
}