diff --git a/packages/common/network/client.ts b/packages/common/network/client.ts new file mode 100644 index 000000000..5211c793f --- /dev/null +++ b/packages/common/network/client.ts @@ -0,0 +1,67 @@ +import axios from "axios"; +import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; + +interface ClientConfig { + baseURL: string; + siteId: string; +} + +class Client { + private static instance: Client; + private axiosInstance: AxiosInstance; + + private constructor(config: ClientConfig) { + this.axiosInstance = axios.create({ + baseURL: config.baseURL, + headers: { + "Content-Type": "application/json", + "X-Site-Id": config.siteId, + }, + withCredentials: true, + }); + } + + public static getInstance(config: ClientConfig): Client { + if (!Client.instance) { + Client.instance = new Client(config); + } + return Client.instance; + } + + public async get>( + url: string, + config?: AxiosRequestConfig + ): Promise { + const response = await this.axiosInstance.get(url, config); + return response; + } + + public async post, D = unknown>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise { + const response = await this.axiosInstance.post(url, data, config); + return response; + } + + public async put, D = unknown>( + url: string, + data?: D, + config?: AxiosRequestConfig + ): Promise { + const response = await this.axiosInstance.put(url, data, config); + return response; + } + + public async delete>( + url: string, + config?: AxiosRequestConfig + ): Promise { + const response = await this.axiosInstance.delete(url, config); + return response; + } +} + +export type { ClientConfig }; +export { Client }; diff --git a/packages/common/network/index.ts b/packages/common/network/index.ts new file mode 100644 index 000000000..5ec76921e --- /dev/null +++ b/packages/common/network/index.ts @@ -0,0 +1 @@ +export * from "./client"; diff --git a/packages/common/network/package.json b/packages/common/network/package.json new file mode 100644 index 000000000..9a479b6bd --- /dev/null +++ b/packages/common/network/package.json @@ -0,0 +1,17 @@ +{ + "name": "@common/network", + "version": "0.0.0", + "private": true, + "main": "./index.ts", + "types": "./index.ts", + "exports": { + ".": "./index.ts" + }, + "dependencies": { + "axios": "^1.8.1" + }, + "devDependencies": { + "@types/node": "^20.11.19", + "typescript": "^5.3.3" + } +} diff --git a/packages/common/network/tsconfig.json b/packages/common/network/tsconfig.json new file mode 100644 index 000000000..8d11d8253 --- /dev/null +++ b/packages/common/network/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "baseUrl": "." + }, + "include": ["."], + "exclude": ["node_modules", "dist"] +}