Open History to see the last commit
1import { Platform } from 'react-native'
2
3// Server URL differs by platform
4// Android emulator: 10.0.2.2 maps to host machine's localhost
5// iOS simulator: localhost works directly
6const SERVER_PORT = 3001
7const BASE_URL = Platform.select({
8 android: `http://10.0.2.2:${SERVER_PORT}`,
9 ios: `http://localhost:${SERVER_PORT}`,
10 default: `http://localhost:${SERVER_PORT}`,
11})
12
13export interface Todo {
14 id: string
15 text: string
16 completed: boolean
17 createdAt: Date
18 updatedAt: Date
19}
20
21interface TodoResponse {
22 id: string
23 text: string
24 completed: boolean
25 createdAt: string
26 updatedAt: string
27}
28
29// Convert API response to Todo with Date objects
30function parseTodo(todo: TodoResponse): Todo {
31 return {
32 ...todo,
33 createdAt: new Date(todo.createdAt),
34 updatedAt: new Date(todo.updatedAt),
35 }
36}
37
38// API client that calls the shared backend server
39export const todoApi = {
40 async getAll(): Promise<Array<Todo>> {
41 const response = await fetch(`${BASE_URL}/api/todos`)
42 if (!response.ok) {
43 throw new Error(`Failed to fetch todos: ${response.status}`)
44 }
45 const data: Array<TodoResponse> = await response.json()
46 return data.map(parseTodo)
47 },
48
49 async create(data: {
50 id?: string
51 text: string
52 completed?: boolean
53 }): Promise<Todo> {
54 const response = await fetch(`${BASE_URL}/api/todos`, {
55 method: 'POST',
56 headers: { 'Content-Type': 'application/json' },
57 body: JSON.stringify(data),
58 })
59 if (!response.ok) {
60 throw new Error(`Failed to create todo: ${response.status}`)
61 }
62 const todo: TodoResponse = await response.json()
63 return parseTodo(todo)
64 },
65
66 async update(
67 id: string,
68 data: { text?: string; completed?: boolean },
69 ): Promise<Todo | null> {
70 const response = await fetch(`${BASE_URL}/api/todos/${id}`, {
71 method: 'PUT',
72 headers: { 'Content-Type': 'application/json' },
73 body: JSON.stringify(data),
74 })
75 if (response.status === 404) {
76 return null
77 }
78 if (!response.ok) {
79 throw new Error(`Failed to update todo: ${response.status}`)
80 }
81 const todo: TodoResponse = await response.json()
82 return parseTodo(todo)
83 },
84
85 async delete(id: string): Promise<boolean> {
86 const response = await fetch(`${BASE_URL}/api/todos/${id}`, {
87 method: 'DELETE',
88 })
89 if (response.status === 404) {
90 return false
91 }
92 if (!response.ok) {
93 throw new Error(`Failed to delete todo: ${response.status}`)
94 }
95 return true
96 },
97}