gemma: generate apps/web/src/lib/api.ts
This commit is contained in:
parent
188ecb990c
commit
54b2032348
65
apps/web/src/lib/api.ts
Normal file
65
apps/web/src/lib/api.ts
Normal file
@ -0,0 +1,65 @@
|
||||
import { z } from "@rmpks/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(() => ({}))
|
||||
throw new Error(errorData.message || `API Error: ${response.status}`)
|
||||
}
|
||||
|
||||
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 })
|
||||
})
|
||||
localStorage.setItem("auth_token", data.token)
|
||||
return data
|
||||
},
|
||||
|
||||
logout() {
|
||||
localStorage.removeItem("auth_token")
|
||||
},
|
||||
|
||||
async getMe() {
|
||||
return request("/auth/me")
|
||||
},
|
||||
|
||||
async listTimeEntries(opts?: Record<string, string>) {
|
||||
const query = new URLSearchParams(opts).toString()
|
||||
const endpoint = query ? `/time-entries?${query}` : "/time-entries"
|
||||
return request(`/time-entries${query ? `?${query}` : ""}`)
|
||||
},
|
||||
|
||||
async createTimeEntry(data: z.infer<typeof z.TimeEntrySchema>) {
|
||||
return request("/time-entries", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data)
|
||||
})
|
||||
},
|
||||
|
||||
async deleteTimeEntry(id: string) {
|
||||
return request(`/time-entries/${id}`, {
|
||||
method: "DELETE"
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user