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

40 lines
1.0 KiB
JavaScript
Raw Permalink Normal View History

2024-04-10 10:26:40 +02:00
const { apiSsrBaseURL } = require("../config")
2023-11-15 08:00:12 +01:00
/**
* api request via server, cache result in context.ssrCache
* should be elimated in client code via tree shaking
*
* @param {string} cacheKey
* @param {string} endpoint
2024-04-10 10:26:40 +02:00
* @param {string} query
2023-11-15 08:00:12 +01:00
* @param {ApiOptions} options
2024-04-10 10:26:40 +02:00
* @returns {ApiResult<any>}
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-04-10 10:26:40 +02:00
const response = context.http.fetch(apiSsrBaseURL + url, {
2023-11-15 08:00:12 +01:00
method: options.method,
headers: options.headers,
})
2024-04-10 10:26:40 +02:00
// console.log(JSON.stringify(response.headers, null, 2))
2023-11-15 08:00:12 +01:00
const json = response.body.json()
2024-04-10 10:26:40 +02:00
const count = parseInt(response.headers["X-Results-Count"] || "0")
2023-11-15 08:00:12 +01:00
// 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,
}