import { token } from './utils' const DEV_URL = 'http://localhost:8091' const PROD_URL = 'https://shop-api.softwarrior.ru' const isDEV_HOST = (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') && window.location.port === '5173' export type ResponseData = { error?: string success?: Array } type HeaderType = HeadersInit & { authorization?: string } const DEFAULT_HEADERS: HeaderType = { 'content-type': 'application/json', } export interface NetworkApi { request: (endpoint: string, options?: RequestInit) => Promise } class Network implements NetworkApi { private _baseUrl: string private _headers: HeaderType constructor() { if (import.meta.env.DEV && isDEV_HOST) { this._baseUrl = DEV_URL } else { this._baseUrl = PROD_URL } this._headers = DEFAULT_HEADERS } private getStringURL(endpoint: string): string { return `${this._baseUrl}/${endpoint.replace(/^\//, '')}` } private async onResponse(res: Response): Promise { return res.ok ? res.json() : res.json().then(data => Promise.reject(data)) } async request(endpoint: string, options?: RequestInit) { const tokenStr = token.load() if (tokenStr) { this._headers.authorization = `Bearer ${tokenStr}` } else { this._headers.authorization = undefined } const res = await fetch(this.getStringURL(endpoint), { method: 'GET', ...options, headers: { ...this._headers, ...options?.headers }, }) return await this.onResponse(res) } } export const networkApi: NetworkApi = new Network()