Skip to content

Instantly share code, notes, and snippets.

@GoodnessEzeokafor
Forked from Orbis25/IRepository.ts
Created January 24, 2022 10:58
Show Gist options
  • Save GoodnessEzeokafor/7b64b4c3c9d0522b41a6fdcab900f197 to your computer and use it in GitHub Desktop.
Save GoodnessEzeokafor/7b64b4c3c9d0522b41a6fdcab900f197 to your computer and use it in GitHub Desktop.
Simple Repository Pattern in TypeScript with axios
import { AxiosResponse } from "axios";
import { AxiosConfig } from "../../api";
export interface IRead<T> {
getAll(route: string, params?: string): Promise<AxiosResponse<T[]>>;
getById(route: string, id: string): Promise<AxiosResponse<T>>;
getPaginatedList(route: string, params?: string): Promise<AxiosResponse<T[]>>;
}
export interface IWrite<T> {
add(route: string, model: T): Promise<AxiosResponse<T | boolean>>;
update(route: string, model: T): Promise<AxiosResponse<T | boolean>>;
remove(route: string, id: string): Promise<AxiosResponse<boolean>>;
}
export interface IRepository<T> extends IWrite<T>, IRead<T> {}
/////////////////Implementation///////////////////////////////
export class Repository<T> implements IRepository<T> {
async getPaginatedList(
route: string,
params?: string | undefined
): Promise<AxiosResponse<T[]>> {
route = params ? `${route}?${params}` : route;
return await AxiosConfig.get(route);
}
async add(route: string, model: T): Promise<AxiosResponse<boolean | T>> {
return await AxiosConfig.post(route, model);
}
async update(route: string, model: T): Promise<AxiosResponse<boolean | T>> {
return await AxiosConfig.put(route, model);
}
async remove(route: string, id: string): Promise<AxiosResponse<boolean>> {
return await AxiosConfig.delete(`${route}/${id}`);
}
async getAll(route: string, params?: string): Promise<AxiosResponse<T[]>> {
route = params ? `${route}?${params}` : route;
return await AxiosConfig.get(route);
}
async getById(route: string, id: string): Promise<AxiosResponse<T>> {
return await AxiosConfig.get(`${route}/${id}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment