| 1 | 'use server'; |
| 2 | |
| 3 | import fs from 'fs/promises'; |
| 4 | |
| 5 | export interface Todo { |
| 6 | id: number; |
| 7 | title: string; |
| 8 | description: string; |
| 9 | dueDate: string; |
| 10 | isComplete: boolean; |
| 11 | } |
| 12 | |
| 13 | export async function getTodos(): Promise<Todo[]> { |
| 14 | try { |
| 15 | let contents = await fs.readFile('todos.json', 'utf8'); |
| 16 | return JSON.parse(contents); |
| 17 | } catch { |
| 18 | await fs.writeFile('todos.json', '[]'); |
| 19 | return []; |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | export async function getTodo(id: number): Promise<Todo | undefined> { |
| 24 | let todos = await getTodos(); |
| 25 | return todos.find(todo => todo.id === id); |
| 26 | } |
| 27 | |
| 28 | export async function createTodo(formData: FormData) { |
| 29 | let todos = await getTodos(); |
| 30 | let title = formData.get('title'); |
| 31 | let description = formData.get('description'); |
| 32 | let dueDate = formData.get('dueDate'); |
| 33 | let id = todos.length > 0 ? Math.max(...todos.map(todo => todo.id)) + 1 : 0; |
| 34 | todos.push({ |
| 35 | id, |
| 36 | title: typeof title === 'string' ? title : '', |
| 37 | description: typeof description === 'string' ? description : '', |
| 38 | dueDate: typeof dueDate === 'string' ? dueDate : new Date().toISOString(), |
| 39 | isComplete: false, |
| 40 | }); |
| 41 | await fs.writeFile('todos.json', JSON.stringify(todos)); |
| 42 | } |
| 43 | |
| 44 | export async function updateTodo(id: number, formData: FormData) { |
| 45 | let todos = await getTodos(); |
| 46 | let title = formData.get('title'); |
| 47 | let description = formData.get('description'); |
| 48 | let dueDate = formData.get('dueDate'); |
| 49 | let todo = todos.find(todo => todo.id === id); |
| 50 | if (todo) { |
| 51 | todo.title = typeof title === 'string' ? title : ''; |
| 52 | todo.description = typeof description === 'string' ? description : ''; |
| 53 | todo.dueDate = |
| 54 | typeof dueDate === 'string' ? dueDate : new Date().toISOString(); |
| 55 | await fs.writeFile('todos.json', JSON.stringify(todos)); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export async function setTodoComplete(id: number, isComplete: boolean) { |
| 60 | let todos = await getTodos(); |
| 61 | let todo = todos.find(todo => todo.id === id); |
| 62 | if (todo) { |
| 63 | todo.isComplete = isComplete; |
| 64 | await fs.writeFile('todos.json', JSON.stringify(todos)); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | export async function deleteTodo(id: number) { |
| 69 | let todos = await getTodos(); |
| 70 | let index = todos.findIndex(todo => todo.id === id); |
| 71 | if (index >= 0) { |
| 72 | todos.splice(index, 1); |
| 73 | await fs.writeFile('todos.json', JSON.stringify(todos)); |
| 74 | } |
| 75 | } |