Open History to see the last commit
1import { readFileSync, writeFileSync } from 'node:fs'
2import { dirname, join } from 'node:path'
3import { fileURLToPath } from 'node:url'
4import cors from 'cors'
5import express from 'express'
6
7const app = express()
8const PORT = 3001
9const DATA_FILE = join(dirname(fileURLToPath(import.meta.url)), 'todos.json')
10
11app.use(cors())
12app.use(express.json())
13
14// Types
15interface Todo {
16 id: string
17 text: string
18 completed: boolean
19 createdAt: string
20 updatedAt: string
21}
22
23// In-memory store
24const todosStore = new Map<string, Todo>()
25
26// Helper function to generate IDs
27function generateId(): string {
28 return Math.random().toString(36).substring(2) + Date.now().toString(36)
29}
30
31// Load persisted data or seed with initial data
32function loadData() {
33 try {
34 const raw = readFileSync(DATA_FILE, 'utf-8')
35 const todos: Array<Todo> = JSON.parse(raw)
36 todos.forEach((todo) => todosStore.set(todo.id, todo))
37 console.log(`Loaded ${todos.length} todos from ${DATA_FILE}`)
38 } catch {
39 console.log(`No existing data file, starting empty`)
40 }
41}
42
43function saveData() {
44 writeFileSync(
45 DATA_FILE,
46 JSON.stringify(Array.from(todosStore.values()), null, 2),
47 )
48}
49
50loadData()
51
52// Simulate network delay
53const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
54
55// GET all todos
56app.get('/api/todos', async (_req, res) => {
57 console.log('GET /api/todos')
58 await delay(200)
59 const todos = Array.from(todosStore.values()).sort(
60 (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
61 )
62 res.json(todos)
63})
64
65// POST create todo
66app.post('/api/todos', async (req, res) => {
67 console.log('POST /api/todos', req.body)
68 await delay(200)
69
70 const { id, text, completed } = req.body
71 if (!text || text.trim() === '') {
72 return res.status(400).json({ error: 'Todo text is required' })
73 }
74
75 const now = new Date().toISOString()
76 const todo: Todo = {
77 id: id || generateId(),
78 text,
79 completed: completed ?? false,
80 createdAt: now,
81 updatedAt: now,
82 }
83 todosStore.set(todo.id, todo)
84 saveData()
85 res.status(201).json(todo)
86})
87
88// PUT update todo
89app.put('/api/todos/:id', async (req, res) => {
90 console.log('PUT /api/todos/' + req.params.id, req.body)
91 await delay(200)
92
93 const existing = todosStore.get(req.params.id)
94 if (!existing) {
95 return res.status(404).json({ error: 'Todo not found' })
96 }
97
98 const updated: Todo = {
99 ...existing,
100 ...req.body,
101 updatedAt: new Date().toISOString(),
102 }
103 todosStore.set(req.params.id, updated)
104 saveData()
105 res.json(updated)
106})
107
108// DELETE todo
109app.delete('/api/todos/:id', async (req, res) => {
110 console.log('DELETE /api/todos/' + req.params.id)
111 await delay(200)
112
113 if (!todosStore.delete(req.params.id)) {
114 return res.status(404).json({ error: 'Todo not found' })
115 }
116 saveData()
117 res.json({ success: true })
118})
119
120app.listen(PORT, '0.0.0.0', () => {
121 console.log(`Server running at http://0.0.0.0:${PORT}`)
122 console.log(`\nFor Android emulator, use: http://10.0.2.2:${PORT}`)
123 console.log(`For iOS simulator, use: http://localhost:${PORT}`)
124})