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