@bit-ui-libs/common
Version:
This library was generated with [Nx](https://nx.dev).
70 lines (58 loc) • 2.35 kB
text/typescript
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
export type BaseServiceOptions = {
// If this is not passed then the service will create
// its own axios instance.
axiosInstance?: AxiosInstance;
apiUrl: string;
};
export class BaseService {
private axiosInstance: AxiosInstance;
protected apiUrl!: string;
protected coreApiServicePrefix: string;
protected coreApiUrl: string;
constructor(opts: BaseServiceOptions) {
this.axiosInstance =
opts.axiosInstance ??
axios.create({
timeout: 15000,
validateStatus: (status) => status >= 200 && status < 300,
});
this.apiUrl = opts.apiUrl;
this.coreApiServicePrefix = 'core-events';
this.coreApiUrl = `${this.apiUrl}/${this.coreApiServicePrefix}`;
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
protected async beforeQuery(params?: object) {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
protected async beforeMutation(data: object) {}
// API Generic functions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async get<TRes, TParams extends object = NonNullable<unknown>>(
url: string,
params?: TParams,
options?: AxiosRequestConfig<TParams>
) {
this.beforeQuery(params);
return this.axiosInstance.get(url, { params, ...options }).then((res) => res.data as TRes);
}
public async post<TRes, TVars extends object>(url: string, data: TVars, config?: AxiosRequestConfig<TVars>) {
this.beforeMutation(data);
return this.axiosInstance.post(url, data, config).then((res) => res.data as TRes);
}
public async put<TRes, TVars extends object>(url: string, data: TVars, config?: AxiosRequestConfig<TVars>) {
this.beforeMutation(data);
return this.axiosInstance.put(url, data, config).then((res) => res.data as TRes);
}
public async patch<TRes, TVars extends object>(url: string, data: TVars) {
this.beforeMutation(data);
return this.axiosInstance.patch(url, data).then((res) => res.data as TRes);
}
public async delete<TRes, TParams extends object = NonNullable<unknown>>(
url: string,
params?: TParams,
config?: AxiosRequestConfig
) {
this.beforeQuery(params);
return this.axiosInstance.delete(url, { params, ...config }).then((res) => res.data as TRes);
}
}