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.
63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import { token } from './utils'
|
|
|
|
const DEV_URL = '/dev_api'
|
|
const PROD_URL = 'https://shop.softwarrior.ru:8091'
|
|
|
|
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) {
|
|
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()
|