storage.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { FileStorage } from "@flystorage/file-storage";
  2. import { LocalStorageAdapter } from "@flystorage/local-fs";
  3. import fs from "fs/promises";
  4. import { Log } from "../util/log";
  5. import { App } from "../app";
  6. import { AppPath } from "../app/path";
  7. import { Bus } from "../bus";
  8. import z from "zod/v4";
  9. export namespace Storage {
  10. const log = Log.create({ service: "storage" });
  11. export const Event = {
  12. Write: Bus.event(
  13. "storage.write",
  14. z.object({ key: z.string(), content: z.any() }),
  15. ),
  16. };
  17. const state = App.state("storage", async () => {
  18. const app = await App.use();
  19. const storageDir = AppPath.storage(app.root);
  20. await fs.mkdir(storageDir, { recursive: true });
  21. const storage = new FileStorage(new LocalStorageAdapter(storageDir));
  22. log.info("created", { path: storageDir });
  23. return {
  24. storage,
  25. };
  26. });
  27. export async function readJSON<T>(key: string) {
  28. const storage = await state().then((x) => x.storage);
  29. const data = await storage.readToString(key + ".json");
  30. return JSON.parse(data) as T;
  31. }
  32. export async function writeJSON<T>(key: string, content: T) {
  33. const storage = await state().then((x) => x.storage);
  34. const json = JSON.stringify(content);
  35. await storage.write(key + ".json", json);
  36. Bus.publish(Event.Write, { key, content });
  37. }
  38. export async function* list(prefix: string) {
  39. try {
  40. const storage = await state().then((x) => x.storage);
  41. const list = storage.list(prefix);
  42. for await (const item of list) {
  43. yield item.path.slice(0, -5);
  44. }
  45. } catch {
  46. return;
  47. }
  48. }
  49. }