Stock/pages.ts

54 lines
1.4 KiB
TypeScript
Raw Permalink 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();
}
}
})();
2023-10-26 22:10:47 +09:00
const closeHandler = () => {
2023-07-23 00:32:54 +09:00
watcherRef.close();
2023-10-26 22:10:47 +09:00
};
Deno.addSignalListener("SIGINT", closeHandler);
return ()=>{
Deno.removeSignalListener("SIGINT", closeHandler);
closeHandler();
}
2023-07-23 00:32:54 +09:00
}
let pages_meta: PageDescription[] = [];
let mtime = 0;
2023-10-26 22:10:47 +09:00
let lastest_disposer = () => {};
2023-07-23 00:32:54 +09:00
export async function get_pages_meta(): Promise<[PageDescription[],number]>{
2023-10-26 22:10:47 +09:00
if (pages_meta.length == 0) {
2023-07-23 00:32:54 +09:00
pages_meta = await readPagesDescription();
mtime = Date.now();
2023-10-26 22:10:47 +09:00
lastest_disposer();
lastest_disposer = watchFile(PAGES_PATH, async () => {
2023-07-23 00:32:54 +09:00
pages_meta = await readPagesDescription();
mtime = Date.now();
});
}
return [pages_meta, mtime];
}