wedding-planner-frontend/app/api/abstract-api.tsx
Manuel Bustillo 501bb3a81a
All checks were successful
Playwright Tests / test (pull_request) Has been skipped
Check usage of free licenses / build-static-assets (pull_request) Successful in 1m12s
Add copyright notice / copyright_notice (pull_request) Successful in 1m32s
Build Nginx-based docker image / build-static-assets (push) Successful in 6m2s
Update copyright assignment to cover 2025 and include all contributors
2025-01-13 21:36:52 +01:00

77 lines
2.5 KiB
TypeScript

/* Copyright (C) 2024-2025 LibreWeddingPlanner contributors*/
import { Entity } from '@/app/lib/definitions';
import { getCsrfToken, getSlug } from '@/app/lib/utils';
export interface Api<T extends Entity> {
getAll(serializable: Serializable<T> ,callback: (objets: T[]) => void): void;
get(serializable: Serializable<T>, id: string, callback: (object: T) => void): void;
create(serializable: Serializable<T>, object: T, callback: () => void): void;
update(serializable: Serializable<T>, object: T, callback: () => void): void;
destroy(serializable: Serializable<T>, object: T, callback: () => void): void;
}
export interface Serializable<T> {
fromJson(json: any): T;
toJson(object: T): string;
apiPath(): string;
}
export class AbstractApi<T extends Entity> implements Api<T> {
getAll(serializable: Serializable<T>, callback: (objets: T[]) => void): void {
fetch(`/api/${getSlug()}/${serializable.apiPath()}`)
.then((response) => response.json())
.then((data) => {
callback(data.map((record: any) => {
return serializable.fromJson(record);
}));
}, (error) => {
return [];
});
}
get(serializable: Serializable<T>, id: string, callback: (object: T) => void): void {
fetch(`/api/${getSlug()}/${serializable.apiPath()}/${id}`)
.then((response) => response.json())
.then((data) => {
callback(serializable.fromJson(data));
}, (error) => {
return [];
});
}
update(serializable: Serializable<T>, object: T, callback: () => void): void {
fetch(`/api/${getSlug()}/${serializable.apiPath()}/${object.id}`, {
method: 'PUT',
body: serializable.toJson(object),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
}).then(callback)
.catch((error) => console.error(error));
}
create(serializable: Serializable<T>, object: T, callback: () => void): void {
fetch(`/api/${getSlug()}/${serializable.apiPath()}`, {
method: 'POST',
body: serializable.toJson(object),
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': getCsrfToken(),
}
}).then(callback)
.catch((error) => console.error(error));
}
destroy(serializable: Serializable<T>, object: T, callback: () => void): void {
fetch(`/api/${getSlug()}/${serializable.apiPath()}/${object.id}`, {
method: 'DELETE',
headers: {
'X-CSRF-TOKEN': getCsrfToken(),
}
}).then(callback)
.catch((error) => console.error(error));
}
}