Stock/pages.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-07-23 00:32:54 +09:00
import { parse } from "https://deno.land/std@0.195.0/yaml/mod.ts";
import { join, fromFileUrl } from "https://deno.land/std@0.193.0/path/mod.ts";
export const PAGES_PATH = join(fromFileUrl(import.meta.url), "../pages.yaml");
export interface PageDescription {
name: string;
description: string;
}
async function readPagesDescription() {
const pagesText = await Deno.readTextFile(PAGES_PATH);
const pages = parse(pagesText) as PageDescription[];
return pages;
}
function watchFile(
path: string,
callback: () => void | Promise<void>,
) {
const watcherRef = Deno.watchFs(path);
(async () => {
for await (const event of watcherRef) {
if (event.kind == "modify") {
await callback();
}
}
})();
Deno.addSignalListener("SIGINT", () => {
watcherRef.close();
});
}
let pages_meta: PageDescription[] = [];
let mtime = 0;
export async function get_pages_meta(): Promise<[PageDescription[],number]>{
if (pages_meta) {
pages_meta = await readPagesDescription();
mtime = Date.now();
watchFile(PAGES_PATH, async () => {
pages_meta = await readPagesDescription();
mtime = Date.now();
});
}
return [pages_meta, mtime];
}