| 1 |
import axios from 'axios' |
| 2 |
import { trimLeadingChar, trimTrailingChar } from './text' |
| 3 |
import type { AxiosRequestConfig, AxiosResponse } from 'axios' |
| 4 |
|
| 5 |
const REST_BASE = window.CODE_SNIPPETS?.restAPI.base ?? '' |
| 6 |
|
| 7 |
const getRestUrl = (endpoint: string): string => |
| 8 |
`${trimTrailingChar(REST_BASE, '/')}/${trimLeadingChar(endpoint, '/')}` |
| 9 |
|
| 10 |
const GET_CACHE: Record<string, AxiosResponse<unknown> | undefined> = {} |
| 11 |
|
| 12 |
export const getCached = <T, D>(endpoint: string, refresh = false, config?: AxiosRequestConfig<D>): Promise<AxiosResponse<T, D>> => |
| 13 |
!refresh && GET_CACHE[endpoint] ? |
| 14 |
Promise.resolve(<AxiosResponse<T, D>> GET_CACHE[endpoint]) : |
| 15 |
axios |
| 16 |
.get<T, AxiosResponse<T, D>, D>(getRestUrl(endpoint), config) |
| 17 |
.then(response => { |
| 18 |
GET_CACHE[endpoint] = response |
| 19 |
return response |
| 20 |
}) |
| 21 |
|