Skip to content

Instantly share code, notes, and snippets.

@Orbis25
Created August 26, 2020 19:38
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Orbis25/9d8a0420697341fd85af90bc0a730694 to your computer and use it in GitHub Desktop.
Save Orbis25/9d8a0420697341fd85af90bc0a730694 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