UNPKG

@assassinonz/exzodus-client

Version:

Axios wrapper with end to end type safety

73 lines (72 loc) 2.36 kB
import * as axios from "axios"; export { axios }; export class ExZodusClient { axios; constructor(_apiDef, baseURL) { this.axios = axios.default.create({ baseURL }); } async get(path, ...[config]) { const axiosConfig = ExZodusClient.buildAxiosConfig("get", path, config); const res = await this.axios.request(axiosConfig); return res; } async post(path, ...[config]) { const axiosConfig = ExZodusClient.buildAxiosConfig("post", path, config); const res = await this.axios.request(axiosConfig); return res; } async put(path, ...[config]) { const axiosConfig = ExZodusClient.buildAxiosConfig("put", path, config); const res = await this.axios.request(axiosConfig); return res; } async patch(path, ...[config]) { const axiosConfig = ExZodusClient.buildAxiosConfig("patch", path, config); const res = await this.axios.request(axiosConfig); return res; } async delete(path, ...[config]) { const axiosConfig = ExZodusClient.buildAxiosConfig("delete", path, config); const res = await this.axios.request(axiosConfig); return res; } isErrorOf(err, method, path, code) { if (!(err instanceof axios.AxiosError)) { return false; } const axiosErr = err; if (axiosErr.config?.method !== method) { return false; } if (axiosErr.config?.url !== path) { return false; } if (axiosErr.response?.status !== code) { return false; } return true; } static replacePathParams(url, path) { let modifiedUrl = url; Object.keys(path).forEach(key => { modifiedUrl = modifiedUrl.replace(`:${key}`, path[key].toString()); }); return modifiedUrl; } static buildAxiosConfig(method, path, config) { if (!config) { return { method, url: path }; } return { method, url: "path" in config ? this.replacePathParams(path, config["path"]) : path, headers: config["header"], params: config["query"], data: config["body"], responseType: config["responseType"] }; } }