104 lines
2.6 KiB
TypeScript
104 lines
2.6 KiB
TypeScript
import type { TimeEntryInsert, CustomerInsert, ProjectInsert } from "@emberclone/shared"
|
|
|
|
const API_BASE = "/api"
|
|
|
|
async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
|
const token = localStorage.getItem("auth_token")
|
|
const headers = new Headers(options.headers)
|
|
|
|
if (token) {
|
|
headers.set("Authorization", `Bearer ${token}`)
|
|
}
|
|
|
|
headers.set("Content-Type", "application/json")
|
|
|
|
const response = await fetch(`${API_BASE}${endpoint}`, {
|
|
...options,
|
|
headers,
|
|
credentials: "include"
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json().catch(() => ({}))
|
|
const err: any = new Error(errorData.message || `API Error: ${response.status}`)
|
|
err.status = response.status
|
|
throw err
|
|
}
|
|
|
|
return response.json()
|
|
}
|
|
|
|
export const api = {
|
|
async login(email: string, password: string) {
|
|
const data = await request<{ token: string }>("/auth/login", {
|
|
method: "POST",
|
|
body: JSON.stringify({ email, password })
|
|
})
|
|
if (data?.token) {
|
|
localStorage.setItem("auth_token", data.token)
|
|
}
|
|
return data
|
|
},
|
|
|
|
logout() {
|
|
localStorage.removeItem("auth_token")
|
|
return request("/auth/logout", { method: "POST" }).catch(() => {})
|
|
},
|
|
|
|
async getMe() {
|
|
return request<{ id: string; email: string; name: string; role: "admin" | "user" }>("/auth/me")
|
|
},
|
|
|
|
async listTimeEntries(opts?: Record<string, string>) {
|
|
const query = opts ? `?${new URLSearchParams(opts).toString()}` : ""
|
|
return request<any[]>(`/time-entries${query}`)
|
|
},
|
|
|
|
async createTimeEntry(data: Partial<TimeEntryInsert>) {
|
|
return request("/time-entries", {
|
|
method: "POST",
|
|
body: JSON.stringify(data)
|
|
})
|
|
},
|
|
|
|
async deleteTimeEntry(id: string) {
|
|
return request(`/time-entries/${id}`, {
|
|
method: "DELETE"
|
|
})
|
|
},
|
|
|
|
async listCustomers() {
|
|
return request<any[]>( "/customers")
|
|
},
|
|
|
|
async createCustomer(data: Partial<CustomerInsert>) {
|
|
return request("/customers", {
|
|
method: "POST",
|
|
body: JSON.stringify(data)
|
|
})
|
|
},
|
|
|
|
async deleteCustomer(id: string) {
|
|
return request(`/customers/${id}`, {
|
|
method: "DELETE"
|
|
})
|
|
},
|
|
|
|
async listProjects(opts?: Record<string, string>) {
|
|
const query = opts ? `?${new URLSearchParams(opts).toString()}` : ""
|
|
return request<any[]>(`/projects${query}`)
|
|
},
|
|
|
|
async createProject(data: Partial<ProjectInsert>) {
|
|
return request("/projects", {
|
|
method: "POST",
|
|
body: JSON.stringify(data)
|
|
})
|
|
},
|
|
|
|
async deleteProject(id: string) {
|
|
return request(`/projects/${id}`, {
|
|
method: "DELETE"
|
|
})
|
|
}
|
|
} |