2025-09-05 14:59:21 +08:00

38 lines
1.5 KiB
JavaScript

import { isPreview } from "./preview.js";
import { cacheStorage, chunksFromArray, getContent, getContentsList } from "./storage.js";
import { useRuntimeConfig } from "#imports";
export async function getContentIndex(event) {
const defaultLocale = useRuntimeConfig().content.defaultLocale;
let contentIndex = await cacheStorage().getItem("content-index.json");
if (!contentIndex) {
const data = await getContentsList(event);
contentIndex = data.reduce((acc, item) => {
acc[item._path] = acc[item._path] || [];
if (item._locale === defaultLocale) {
acc[item._path].unshift(item._id);
} else {
acc[item._path].push(item._id);
}
return acc;
}, {});
await cacheStorage().setItem("content-index.json", contentIndex);
}
return contentIndex;
}
export async function getIndexedContentsList(event, query) {
const params = query.params();
const path = params?.where?.find((wh) => wh._path)?._path;
if (!isPreview(event) && !params.surround && !params.dirConfig && (typeof path === "string" || path instanceof RegExp)) {
const index = await getContentIndex(event);
const keys = Object.keys(index).filter((key) => path.test ? path.test(key) : key === String(path)).flatMap((key) => index[key]);
const keyChunks = [...chunksFromArray(keys, 10)];
const contents = [];
for await (const chunk of keyChunks) {
const result = await Promise.all(chunk.map((key) => getContent(event, key)));
contents.push(...result);
}
return contents;
}
return getContentsList(event);
}