-
-
Save GoodnessEzeokafor/7b64b4c3c9d0522b41a6fdcab900f197 to your computer and use it in GitHub Desktop.
Simple Repository Pattern in TypeScript with axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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