import { AxiosInstance, AxiosRequestConfig } from 'axios'; import { Methods, Id, Shape, Count } from '../../types'; import { BaseRequestModelInterface } from '../interfaces'; export class BaseRequestModel implements BaseRequestModelInterface { protected api: AxiosInstance; public basePath: string; constructor(api: AxiosInstance, basePath: string) { this.api = api; this.basePath = basePath; this.request = this.request.bind(this); this.post = this.post.bind(this); this.getAll = this.getAll.bind(this); this.getById = this.getById.bind(this); this.count = this.count.bind(this); this.patchById = this.patchById.bind(this); this.patchAll = this.patchAll.bind(this); this.putById = this.putById.bind(this); this.deleteById = this.deleteById.bind(this); } async request(config: AxiosRequestConfig): Promise { const { data } = await this.api.request(config); return data; } async post(item: Omit): Promise { return this.request({ url: this.basePath, method: Methods.POST, data: item, }); } async getAll(filter?: Shape): Promise { return this.request({ url: this.basePath, params: filter ? { filter } : undefined, method: Methods.GET, }); } async getById(id: Id, filter?: Shape): Promise { return this.request({ url: `${this.basePath}/${id}`, method: Methods.GET, params: filter ? { filter } : undefined, }); } async count(where?: Shape): Promise { return this.request({ url: `${this.basePath}/count`, method: Methods.GET, params: where ? { where } : undefined, }); } async patchById(id: Id, item: Partial): Promise { await this.request({ url: `${this.basePath}/${id}`, method: Methods.PATCH, data: item, }); } async patchAll(item: Partial, where?: Shape): Promise { return this.request({ url: this.basePath, method: Methods.PATCH, data: item, params: where ? { where } : undefined, }); } async putById(id: Id, item: T): Promise { await this.request({ url: `${this.basePath}/${id}`, method: Methods.PUT, data: item, }); } async deleteById(id: Id): Promise { await this.request({ url: `${this.basePath}/${id}`, method: Methods.DELETE, }); } }