tibi-docs/api/hooks/lib/ssr-server.js

37 lines
1006 B
JavaScript
Raw Normal View History

2023-11-15 08:00:12 +01:00
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
2024-01-27 19:58:35 +01:00
* @returns {ApiResult}
2023-11-15 08:00:12 +01:00
*/
function ssrRequest(cacheKey, endpoint, query, options) {
let url = endpoint + (query ? "?" + query : "")
// console.log("############ FETCHING ", apiSsrBaseURL + url)
2024-01-27 19:58:35 +01:00
const response = context.http.fetch(apiSsrBaseURL + "/" + url, {
2023-11-15 08:00:12 +01:00
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,
}