52 lines
1.3 KiB
JavaScript
52 lines
1.3 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,
|
|
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) => {
|
|
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);
|
|
}
|