This commit is contained in:
36
api/hooks/lib/ssr-server.js
Normal file
36
api/hooks/lib/ssr-server.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const { apiSsrBaseURL, ssrPublishCheckCollections } = require("../config")
|
||||
|
||||
/**
|
||||
* api request via server, cache result in context.ssrCache
|
||||
* should be elimated in client code via tree shaking
|
||||
*
|
||||
* @param {string} cacheKey
|
||||
* @param {string} endpoint
|
||||
* @param {ApiOptions} options
|
||||
* @returns {ApiResult}
|
||||
*/
|
||||
function ssrRequest(cacheKey, endpoint, query, options) {
|
||||
let url = endpoint + (query ? "?" + query : "")
|
||||
|
||||
// console.log("############ FETCHING ", apiSsrBaseURL + url)
|
||||
|
||||
const response = context.http.fetch(apiSsrBaseURL + "/" + url, {
|
||||
method: options.method,
|
||||
headers: options.headers,
|
||||
})
|
||||
|
||||
const json = response.body.json()
|
||||
const count = parseInt(response.headers["x-results-count"] || "0")
|
||||
|
||||
// json is go data structure and incompatible with js, so we need to convert it
|
||||
const r = { data: JSON.parse(JSON.stringify(json)), count: count }
|
||||
|
||||
// @ts-ignore
|
||||
context.ssrCache[cacheKey] = r
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ssrRequest,
|
||||
}
|
||||
@@ -110,6 +110,7 @@ function apiRequest(endpoint, options, body) {
|
||||
|
||||
// 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__ && options?.method === "GET") {
|
||||
@@ -153,6 +154,7 @@ function apiRequest(endpoint, options, body) {
|
||||
} else {
|
||||
// client
|
||||
let url = endpoint + (query ? "?" + query : "")
|
||||
console.log("URL:", url)
|
||||
const requestOptions = {
|
||||
method,
|
||||
mode: "cors",
|
||||
|
||||
@@ -38,8 +38,6 @@ function obj2str(obj) {
|
||||
if (obj) return obj
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* clear SSR cache
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user