示例工程 11-main-process-services

11-main-process-services/app/main/services/notes-service.ts

typescript · 3.5 KB

import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { ServiceError, type NoteMeta, type NoteRead } from "../../shared/ipc";

const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
const MAX_BYTES = 64 * 1024;

export type NotesService = {
  list(): Promise<NoteMeta[]>;
  read(id: string): Promise<NoteRead>;
  write(id: string, content: string): Promise<NoteMeta>;
  remove(id: string): Promise<void>;
  reset(): Promise<void>;
};

export function createNotesService(options: {
  dir: string;
  maxBytes?: number;
}): NotesService {
  const maxBytes = options.maxBytes ?? MAX_BYTES;

  const assertId = (id: string): void => {
    if (!ID_PATTERN.test(id)) {
      throw new ServiceError("BAD_ID", "非法的笔记 id", "id");
    }
  };

  const fileOf = (id: string): string => {
    assertId(id);
    return path.join(options.dir, `${id}.md`);
  };

  const ensureDir = async (): Promise<void> => {
    await fs.mkdir(options.dir, { recursive: true });
  };

  return {
    async list(): Promise<NoteMeta[]> {
      await ensureDir();
      const entries = await fs.readdir(options.dir, { withFileTypes: true });
      const notes: NoteMeta[] = [];
      for (const entry of entries) {
        if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
        const id = entry.name.slice(0, -3);
        if (!ID_PATTERN.test(id)) continue;
        const stat = await fs.stat(path.join(options.dir, entry.name));
        notes.push({
          id,
          sizeBytes: stat.size,
          updatedAt: stat.mtimeMs,
        });
      }
      return notes.sort((left, right) => right.updatedAt - left.updatedAt);
    },

    async read(id: string): Promise<NoteRead> {
      const file = fileOf(id);
      try {
        const stat = await fs.stat(file);
        if (stat.size > maxBytes) {
          throw new ServiceError(
            "TOO_LARGE",
            `笔记超过 ${maxBytes} 字节上限`,
            "id",
          );
        }
        return { id, content: await fs.readFile(file, "utf8") };
      } catch (error) {
        if (error instanceof ServiceError) throw error;
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
          throw new ServiceError("NOT_FOUND", "笔记不存在", "id");
        }
        throw error;
      }
    },

    async write(id: string, content: string): Promise<NoteMeta> {
      await ensureDir();
      const file = fileOf(id);
      if (Buffer.byteLength(content, "utf8") > maxBytes) {
        throw new ServiceError(
          "TOO_LARGE",
          `笔记超过 ${maxBytes} 字节上限`,
          "id",
        );
      }
      const temp = path.join(options.dir, `.${id}.${randomUUID()}.tmp`);
      await fs.writeFile(temp, content, "utf8");
      await fs.rename(temp, file);
      const stat = await fs.stat(file);
      return { id, sizeBytes: stat.size, updatedAt: stat.mtimeMs };
    },

    async remove(id: string): Promise<void> {
      const file = fileOf(id);
      try {
        await fs.unlink(file);
      } catch (error) {
        if ((error as NodeJS.ErrnoException).code === "ENOENT") {
          throw new ServiceError("NOT_FOUND", "笔记不存在", "id");
        }
        throw error;
      }
    },

    async reset(): Promise<void> {
      await ensureDir();
      const entries = await fs.readdir(options.dir);
      await Promise.all(
        entries
          .filter((name) => name.endsWith(".md") || name.endsWith(".tmp"))
          .map((name) => fs.rm(path.join(options.dir, name), { force: true })),
      );
    },
  };
}