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: { text: string; completed?: boolean }): Promise<Todo> {
50 const response = await fetch(`${BASE_URL}/api/todos`, {
51 method: 'POST',
52 headers: { 'Content-Type': 'application/json' },
53 body: JSON.stringify(data),
54 })
55 if (!response.ok) {
56 throw new Error(`Failed to create todo: ${response.status}`)
57 }
58 const todo: TodoResponse = await response.json()
59 return parseTodo(todo)
60 },
61
62 async update(
63 id: string,
64 data: { text?: string; completed?: boolean },
65 ): Promise<Todo | null> {
66 const response = await fetch(`${BASE_URL}/api/todos/${id}`, {
67 method: 'PUT',
68 headers: { 'Content-Type': 'application/json' },
69 body: JSON.stringify(data),
70 })
71 if (response.status === 404) {
72 return null
73 }
74 if (!response.ok) {
75 throw new Error(`Failed to update todo: ${response.status}`)
76 }
77 const todo: TodoResponse = await response.json()
78 return parseTodo(todo)
79 },
80
81 async delete(id: string): Promise<boolean> {
82 const response = await fetch(`${BASE_URL}/api/todos/${id}`, {
83 method: 'DELETE',
84 })
85 if (response.status === 404) {
86 return false
87 }
88 if (!response.ok) {
89 throw new Error(`Failed to delete todo: ${response.status}`)
90 }
91 return true
92 },
93}