|
| 1 | +import * as fsPromises from "node:fs/promises"; |
| 2 | +import * as path from "node:path"; |
| 3 | +import * as yaml from "js-yaml"; |
| 4 | + |
| 5 | +const LIBRARY_DIR = path.join(process.cwd(), "library"); |
| 6 | + |
| 7 | +export type LibraryEntry = { |
| 8 | + title: string; |
| 9 | + handle: string; |
| 10 | + fullPath: string; |
| 11 | +}; |
| 12 | + |
| 13 | +const cache: Map<string, LibraryEntry> = new Map(); |
| 14 | +const all: LibraryEntry[] = []; |
| 15 | + |
| 16 | +async function initialize() { |
| 17 | + const fileNames = await fsPromises.readdir(LIBRARY_DIR); |
| 18 | + for await (const fileName of fileNames) { |
| 19 | + const fullPath = path.join(LIBRARY_DIR, fileName); |
| 20 | + console.log(`filename=${fullPath}`); |
| 21 | + |
| 22 | + const raw = await fsPromises.readFile(fullPath, "utf-8"); |
| 23 | + const parsed = yaml.load(raw, { |
| 24 | + fullPath, |
| 25 | + schema: yaml.JSON_SCHEMA, |
| 26 | + }) as LibraryEntry; |
| 27 | + parsed.fullPath = fullPath; |
| 28 | + |
| 29 | + cache.set(parsed.handle, parsed); |
| 30 | + //LATER: validate w/JSON schema |
| 31 | + all.push(parsed); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function get(handle: string) { |
| 36 | + |
| 37 | + const entry = cache.get(handle); |
| 38 | + |
| 39 | + if (!entry) { |
| 40 | + throw new Error(`Unknown catalog entry ${handle}`); |
| 41 | + } |
| 42 | + |
| 43 | + return entry; |
| 44 | +} |
| 45 | + |
| 46 | +function getAll(): LibraryEntry[] { |
| 47 | + |
| 48 | + return all; |
| 49 | +} |
| 50 | + |
| 51 | +initialize(); |
| 52 | + |
| 53 | +export { get, getAll, initialize }; |
0 commit comments