1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-07-20 05:39:40 +02:00
mealie/frontend/lib/api/base/base-clients.ts

61 lines
1.9 KiB
TypeScript
Raw Normal View History

import { Recipe } from "../types/recipe";
import { ApiRequestInstance, PaginationData } from "~/lib/api/types/non-generated";
import { QueryValue, route } from "~/lib/api/base/route";
2021-08-01 19:24:47 -08:00
export interface CrudAPIInterface {
requests: ApiRequestInstance;
// Route Properties / Methods
baseRoute: string;
itemRoute(itemId: string | number): string;
// Methods
2021-08-01 19:24:47 -08:00
}
export abstract class BaseAPI {
requests: ApiRequestInstance;
constructor(requests: ApiRequestInstance) {
this.requests = requests;
}
}
export abstract class BaseCRUDAPI<CreateType, ReadType, UpdateType = CreateType>
extends BaseAPI
implements CrudAPIInterface
{
abstract baseRoute: string;
abstract itemRoute(itemId: string | number): string;
async getAll(page = 1, perPage = -1, params = {} as Record<string, QueryValue>) {
params = Object.fromEntries(Object.entries(params).filter(([_, v]) => v !== null && v !== undefined));
return await this.requests.get<PaginationData<ReadType>>(route(this.baseRoute, { page, perPage, ...params }));
}
2022-05-21 21:22:02 +02:00
async createOne(payload: CreateType) {
return await this.requests.post<ReadType>(this.baseRoute, payload);
}
async getOne(itemId: string | number) {
2022-05-21 21:22:02 +02:00
return await this.requests.get<ReadType>(this.itemRoute(itemId));
}
2022-05-21 21:22:02 +02:00
async updateOne(itemId: string | number, payload: UpdateType) {
return await this.requests.put<ReadType, UpdateType>(this.itemRoute(itemId), payload);
}
2022-05-21 21:22:02 +02:00
async patchOne(itemId: string, payload: Partial<UpdateType>) {
return await this.requests.patch<ReadType, Partial<UpdateType>>(this.itemRoute(itemId), payload);
}
async deleteOne(itemId: string | number) {
2022-05-21 21:22:02 +02:00
return await this.requests.delete<ReadType>(this.itemRoute(itemId));
}
async duplicateOne(itemId: string | number, newName: string | undefined) {
return await this.requests.post<Recipe>(`${this.itemRoute(itemId)}/duplicate`, {
name: newName,
});
}
}