Open History to see the last commit
1import { randomUUID } from "node:crypto";
2import { promises as fs } from "node:fs";
3import path from "node:path";
4
5import {
6 type NewTodoInput,
7 type Todo,
8 newTodoInputSchema,
9 todoIdSchema,
10 todoListSchema,
11} from "@acme/contracts";
12
13export class TodoStore {
14 private todos: Todo[] = [];
15 private queue: Promise<void> = Promise.resolve();
16
17 public constructor(private readonly filePath: string) {}
18
19 public async init(): Promise<void> {
20 return this.runExclusive(async () => {
21 await fs.mkdir(path.dirname(this.filePath), { recursive: true });
22
23 try {
24 const raw = await fs.readFile(this.filePath, "utf8");
25 const parsed = todoListSchema.safeParse(JSON.parse(raw));
26
27 if (parsed.success) {
28 this.todos = parsed.data;
29 return;
30 }
31 } catch (error) {
32 if (!isNotFoundError(error)) {
33 throw error;
34 }
35 }
36
37 this.todos = [];
38 await this.persist();
39 });
40 }
41
42 public async list(): Promise<Todo[]> {
43 return this.runExclusive(async () => [...this.todos]);
44 }
45
46 public async add(input: NewTodoInput): Promise<Todo[]> {
47 return this.runExclusive(async () => {
48 const { title } = newTodoInputSchema.parse(input);
49 const todo: Todo = {
50 id: randomUUID(),
51 title,
52 completed: false,
53 createdAt: new Date().toISOString(),
54 };
55
56 this.todos = [todo, ...this.todos];
57 await this.persist();
58 return [...this.todos];
59 });
60 }
61
62 public async toggle(id: string): Promise<Todo[]> {
63 return this.runExclusive(async () => {
64 const parsedId = todoIdSchema.parse(id);
65 this.todos = this.todos.map((todo) =>
66 todo.id === parsedId ? { ...todo, completed: !todo.completed } : todo,
67 );
68
69 await this.persist();
70 return [...this.todos];
71 });
72 }
73
74 public async remove(id: string): Promise<Todo[]> {
75 return this.runExclusive(async () => {
76 const parsedId = todoIdSchema.parse(id);
77 this.todos = this.todos.filter((todo) => todo.id !== parsedId);
78
79 await this.persist();
80 return [...this.todos];
81 });
82 }
83
84 private async persist(): Promise<void> {
85 await fs.writeFile(this.filePath, JSON.stringify(this.todos, null, 2), "utf8");
86 }
87
88 private async runExclusive<T>(operation: () => Promise<T>): Promise<T> {
89 const next = this.queue.then(operation, operation);
90 this.queue = next.then(
91 () => undefined,
92 () => undefined,
93 );
94
95 return next;
96 }
97}
98
99function isNotFoundError(error: unknown): boolean {
100 return (
101 typeof error === "object" &&
102 error !== null &&
103 "code" in error &&
104 (error as { code?: string }).code === "ENOENT"
105 );
106}