med-notes/resource-provider/helper.js
2025-06-26 04:42:51 +00:00

55 lines
1.4 KiB
JavaScript

import { promises as fs } from "fs";
import path from "path";
import { STATIC_DIR, SUBJECTS } from "./constants.js";
export const cache = new Map();
async function populateResources() {
const filenamesRaw = await fs.readdir(STATIC_DIR);
const filenames = filenamesRaw
.filter((file) => file.endsWith(".md"))
.map((file) => file.replace(".md", ""));
const topicResources = {};
filenames.forEach((resourceId) => {
const parts = resourceId.split("_");
const subjectPart = parts[1];
const topicPart = parts[2];
const topicId = `${subjectPart}_${topicPart}`;
topicResources[topicId] ||= [];
topicResources[topicId].push({
id: resourceId,
filename: `${resourceId}.md`,
version: parseInt(parts[3].substring(2)),
});
});
Object.values(topicResources).forEach((resources) => {
resources.sort((a, b) => a.version - b.version);
});
Object.values(SUBJECTS).forEach((subject) => {
Object.values(subject.topics).forEach((topic) => {
if (topic.id in topicResources) {
topic.resources = topicResources[topic.id];
}
});
});
}
export async function getStructure({ refresh = false } = {}) {
const structureKey = "structure";
if (refresh) {
cache.delete(structureKey);
}
if (!cache.has(structureKey)) {
await populateResources();
cache.set(structureKey, SUBJECTS);
}
return cache.get(structureKey);
}