generated from cms/tibi-docs
backend & types
This commit is contained in:
@@ -34,7 +34,10 @@ function obj2str(obj) {
|
||||
|
||||
// fetch polyfill
|
||||
// [MIT License](LICENSE.md) © [Jason Miller](https://jasonformat.com/)
|
||||
const _f = function (url, options) {
|
||||
const _f = function (
|
||||
/** @type {string | URL} */ url,
|
||||
/** @type {{ method?: any; credentials?: any; headers?: any; body?: any; }} */ options
|
||||
) {
|
||||
if (typeof XMLHttpRequest === "undefined") {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
@@ -99,14 +102,18 @@ const _fetch = typeof fetch === "undefined" ? (typeof window === "undefined" ? _
|
||||
*
|
||||
* @param {string} endpoint
|
||||
* @param {ApiOptions} options
|
||||
* @returns {Promise<ApiResult>}
|
||||
* @param {any} body
|
||||
* @returns {Promise<ApiResult<any>>}
|
||||
*/
|
||||
function apiRequest(endpoint, options) {
|
||||
function apiRequest(endpoint, options, body) {
|
||||
// TODO cache only for GET
|
||||
|
||||
// first check cache if on client
|
||||
const cacheKey = obj2str({ endpoint: endpoint, options: options })
|
||||
options.method = options?.method || "GET"
|
||||
|
||||
// @ts-ignore
|
||||
if (typeof window !== "undefined" && window.__SSR_CACHE__) {
|
||||
if (typeof window !== "undefined" && window.__SSR_CACHE__ && options?.method === "GET") {
|
||||
// @ts-ignore
|
||||
const cache = window.__SSR_CACHE__[cacheKey]
|
||||
console.log("SSR:", cacheKey, cache)
|
||||
@@ -115,7 +122,7 @@ function apiRequest(endpoint, options) {
|
||||
}
|
||||
}
|
||||
|
||||
let method = "GET"
|
||||
let method = options?.method || "GET"
|
||||
|
||||
let query = "&count=1"
|
||||
if (options?.filter) query += "&filter=" + encodeURIComponent(JSON.stringify(options.filter))
|
||||
@@ -137,7 +144,7 @@ function apiRequest(endpoint, options) {
|
||||
|
||||
if (options?.headers) headers = { ...headers, ...options.headers }
|
||||
|
||||
if (typeof window === "undefined") {
|
||||
if (typeof window === "undefined" && method === "GET") {
|
||||
// server
|
||||
|
||||
// reference via context from get hook to tree shake in client
|
||||
@@ -147,12 +154,18 @@ function apiRequest(endpoint, options) {
|
||||
} else {
|
||||
// client
|
||||
let url = endpoint + (query ? "?" + query : "")
|
||||
console.log("fetch", apiClientBaseURL + url)
|
||||
return _fetch(apiClientBaseURL + url, {
|
||||
console.log("URL:", url)
|
||||
const requestOptions = {
|
||||
method,
|
||||
mode: "cors",
|
||||
headers,
|
||||
}).then((response) => {
|
||||
}
|
||||
|
||||
if (method === "POST" || method === "PUT") {
|
||||
requestOptions.body = JSON.stringify(body)
|
||||
}
|
||||
|
||||
return _fetch(apiClientBaseURL + url, requestOptions).then((response) => {
|
||||
return response?.json().then((json) => {
|
||||
if (response?.status < 200 || response?.status >= 400) {
|
||||
return Promise.reject({ response, data: json })
|
||||
|
||||
Reference in New Issue
Block a user