/
mmeter-app
/
ui
Обзор
Документация
Войти
/
mmeter-app
/
ui
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
main
src/shared/api/index.ts
88 строк
2 KB
Eugene Yemelin
Clenaup
11 июн 2026, 12:56
11 июн 2026, 12:56
005e638
Код
Авторство
О чём код?
import { HTTPError } from "./errors" import { HTTPMethod } from "./types" export class ApiClient { static root = import.meta.env.VITE_API_ROOT private static _instance: ApiClient private headers: HeadersInit = {} private static contentTypeHeaders = { "Content-Type": "application/json", } private getRoot() { return ApiClient.root } private request( url: string, method: HTTPMethod, params?: Partial<RequestInit> ) { return fetch(`${this.getRoot()}${url}`, { credentials: "include", method, ...params, headers: { ...this.headers, ...params?.headers, }, }) .then((response) => { if (!response.ok) { throw new HTTPError(response.statusText, { code: response.status, }) } if (response.status === 204) { return Promise.resolve({}) } return response.json() }) .catch((e) => console.log(url, e)) } public addHeaders(headers?: HeadersInit) { if (headers) { this.headers = headers } return this } public static get instance() { return this._instance || (this._instance = new this()) } get<R>(url: string): Promise<R> { return this.request(url, HTTPMethod.get, { headers: ApiClient.contentTypeHeaders, }) } post<P, R>(url: string, payload: P): Promise<R> { return this.request(url, HTTPMethod.post, { headers: ApiClient.contentTypeHeaders, body: JSON.stringify(payload), }) } put<P, R>(url: string, payload: P): Promise<R> { return this.request(url, HTTPMethod.put, { headers: ApiClient.contentTypeHeaders, body: JSON.stringify(payload), }) } patch<P, R>(url: string, payload: P): Promise<R> { return this.request(url, HTTPMethod.patch, { headers: ApiClient.contentTypeHeaders, body: JSON.stringify(payload), }) } delete<R>(url: string): Promise<R> { return this.request(url, HTTPMethod.delete) } }