示例工程 11-main-process-services
11-main-process-services/app/.tsc/main/services/notes-service.js
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { ServiceError } from "../../shared/ipc";
const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
const MAX_BYTES = 64 * 1024;
export function createNotesService(options) {
const maxBytes = options.maxBytes ?? MAX_BYTES;
const assertId = (id) => {
if (!ID_PATTERN.test(id)) {
throw new ServiceError("BAD_ID", "非法的笔记 id", "id");
}
};
const fileOf = (id) => {
assertId(id);
return path.join(options.dir, `${id}.md`);
};
const ensureDir = async () => {
await fs.mkdir(options.dir, { recursive: true });
};
return {
async list() {
await ensureDir();
const entries = await fs.readdir(options.dir, { withFileTypes: true });
const notes = [];
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) {
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.code === "ENOENT") {
throw new ServiceError("NOT_FOUND", "笔记不存在", "id");
}
throw error;
}
},
async write(id, content) {
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) {
const file = fileOf(id);
try {
await fs.unlink(file);
}
catch (error) {
if (error.code === "ENOENT") {
throw new ServiceError("NOT_FOUND", "笔记不存在", "id");
}
throw error;
}
},
async reset() {
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 })));
},
};
}
//# sourceMappingURL=notes-service.js.map