Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

index.ts

129 lines3.0 KB

1import fs from 'node:fs'
2import path from 'node:path'
3import { fileURLToPath } from 'node:url'
4import cors from 'cors'
5import express from 'express'
6​
7const __dirname = path.dirname(fileURLToPath(import.meta.url))
8​
9const app = express()
10const PORT = 3001
11​
12app.use(cors())
13app.use(express.json())
14​
15// Types
16interface Todo {
17 id: string
18 text: string
19 completed: boolean
20 createdAt: string
21 updatedAt: string
23​
24// Persist server state to a JSON file so data survives restarts
25const TODOS_FILE = path.join(__dirname, 'todos.json')
26​
27function loadTodos(): Map<string, Todo> {
28 try {
29 const data = JSON.parse(fs.readFileSync(TODOS_FILE, 'utf-8')) as Array<Todo>
30 return new Map(data.map((t) => [t.id, t]))
31 } catch {
32 return new Map()
33 }
35​
36function saveTodos() {
37 fs.writeFileSync(
38 TODOS_FILE,
39 JSON.stringify(Array.from(todosStore.values()), null, 2),
40 )
42​
43const todosStore = loadTodos()
44​
45// Helper function to generate IDs
46function generateId(): string {
47 return Math.random().toString(36).substring(2) + Date.now().toString(36)
49​
50// Simulate network delay
51const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
52​
53// GET all todos
54app.get('/api/todos', async (_req, res) => {
55 console.log('GET /api/todos')
56 await delay(200)
57 const todos = Array.from(todosStore.values()).sort(
58 (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
59 )
60 res.json(todos)
61})
62​
63// POST create todo — accepts client-generated ID
64app.post('/api/todos', async (req, res) => {
65 console.log('POST /api/todos', req.body)
66 await delay(200)
67​
68 const { id, text, completed } = req.body
69 if (!text || text.trim() === '') {
70 return res.status(400).json({ error: 'Todo text is required' })
71 }
72​
73 const now = new Date().toISOString()
74 const todo: Todo = {
75 id: id || generateId(),
76 text,
77 completed: completed ?? false,
78 createdAt: now,
79 updatedAt: now,
80 }
81 todosStore.set(todo.id, todo)
82 saveTodos()
83 res.status(201).json(todo)
84})
85​
86// PUT update todo
87app.put('/api/todos/:id', async (req, res) => {
88 console.log('PUT /api/todos/' + req.params.id, req.body)
89 await delay(200)
90​
91 const existing = todosStore.get(req.params.id)
92 if (!existing) {
93 return res.status(404).json({ error: 'Todo not found' })
94 }
95​
96 const updated: Todo = {
97 ...existing,
98 ...req.body,
99 updatedAt: new Date().toISOString(),
100 }
101 todosStore.set(req.params.id, updated)
102 saveTodos()
103 res.json(updated)
104})
105​
106// DELETE todo
107app.delete('/api/todos/:id', async (req, res) => {
108 console.log('DELETE /api/todos/' + req.params.id)
109 await delay(200)
110​
111 if (!todosStore.delete(req.params.id)) {
112 return res.status(404).json({ error: 'Todo not found' })
113 }
114 saveTodos()
115 res.json({ success: true })
116})
117​
118// DELETE all todos
119app.delete('/api/todos', async (_req, res) => {
120 console.log('DELETE /api/todos (clear all)')
121 await delay(200)
122 todosStore.clear()
123 saveTodos()
124 res.json({ success: true })
125})
126​
127app.listen(PORT, '0.0.0.0', () => {
128 console.log(`Server running at http://0.0.0.0:${PORT}`)
129})