You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.7 KiB
TypeScript

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<object>
}
type HeaderType = HeadersInit & {
authorization?: string
}
const DEFAULT_HEADERS: HeaderType = {
'content-type': 'application/json',
}
export interface NetworkApi {
request: <T>(endpoint: string, options?: RequestInit) => Promise<T>
}
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<T>(res: Response): Promise<T> {
return res.ok ? res.json() : res.json().then(data => Promise.reject(data))
}
async request<T>(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<T>(res)
}
}
export const networkApi: NetworkApi = new Network()