78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
import type { Project, ProjectInsertDTO, ProjectUpdateDTO } from "@workspace/schema";
|
|
|
|
export function useProjectApi() {
|
|
const config = useRuntimeConfig();
|
|
const apiBase = config.public.apiBaseUrl as string;
|
|
const NOT_FOUND = -1;
|
|
|
|
const projects = ref<Project[]>([]);
|
|
const loading = ref(false);
|
|
const error = ref<string | null>(null);
|
|
|
|
async function fetchProjects(): Promise<void> {
|
|
loading.value = true;
|
|
error.value = null;
|
|
try {
|
|
projects.value = await $fetch<Project[]>(`${apiBase}/projects`);
|
|
} catch (err) {
|
|
error.value = err instanceof Error ? err.message : "Unknown error";
|
|
} finally {
|
|
loading.value = false;
|
|
}
|
|
}
|
|
|
|
async function createProject(body: Partial<ProjectInsertDTO>): Promise<Project | null> {
|
|
loading.value = true;
|
|
error.value = null;
|
|
try {
|
|
const created = await $fetch<Project>(`${apiBase}/projects`, {
|
|
method: "POST",
|
|
body,
|
|
});
|
|
projects.value.push(created);
|
|
return created;
|
|
} catch (err) {
|
|
error.value = err instanceof Error ? err.message : "Unknown error";
|
|
return null;
|
|
} finally {
|
|
loading.value = false;
|
|
}
|
|
}
|
|
|
|
async function updateProject(id: string, body: Partial<ProjectUpdateDTO>): Promise<Project | null> {
|
|
loading.value = true;
|
|
error.value = null;
|
|
try {
|
|
const updated = await $fetch<Project>(`${apiBase}/projects/${id}`, {
|
|
method: "PATCH",
|
|
body,
|
|
});
|
|
const idx = projects.value.findIndex((p) => p.id === id);
|
|
if (idx !== NOT_FOUND) projects.value[idx] = updated;
|
|
return updated;
|
|
} catch (err) {
|
|
error.value = err instanceof Error ? err.message : "Unknown error";
|
|
return null;
|
|
} finally {
|
|
loading.value = false;
|
|
}
|
|
}
|
|
|
|
async function deleteProject(id: string): Promise<boolean> {
|
|
loading.value = true;
|
|
error.value = null;
|
|
try {
|
|
await $fetch(`${apiBase}/projects/${id}`, { method: "DELETE" });
|
|
projects.value = projects.value.filter((p) => p.id !== id);
|
|
return true;
|
|
} catch (err) {
|
|
error.value = err instanceof Error ? err.message : "Unknown error";
|
|
return false;
|
|
} finally {
|
|
loading.value = false;
|
|
}
|
|
}
|
|
|
|
return { projects, loading, error, fetchProjects, createProject, updateProject, deleteProject };
|
|
}
|