yarn package upgrades, ssr update
This commit is contained in:
65
api/hooks/lib/ssr-server.js
Normal file
65
api/hooks/lib/ssr-server.js
Normal file
@@ -0,0 +1,65 @@
|
||||
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 {string} query
|
||||
* @param {ApiOptions} options
|
||||
* @returns {ApiResult<any>}
|
||||
*/
|
||||
function ssrRequest(cacheKey, endpoint, query, options) {
|
||||
let url = endpoint + (query ? "?" + query : "")
|
||||
|
||||
if (ssrPublishCheckCollections.includes(endpoint)) {
|
||||
// @ts-ignore
|
||||
let validUntil = context.ssrCacheValidUntil
|
||||
|
||||
// check in db for publish date to invalidate cache
|
||||
const _optionsPublishSearch = Object.assign(
|
||||
{},
|
||||
{ filter: options?.filter },
|
||||
{
|
||||
selector: { publishDate: 1 },
|
||||
// projection: null,
|
||||
}
|
||||
)
|
||||
const publishSearch = context.db.find(endpoint, _optionsPublishSearch)
|
||||
publishSearch?.forEach((item) => {
|
||||
const publishDate = item.publishDate ? new Date(item.publishDate.unixMilli()) : null
|
||||
|
||||
if (publishDate && publishDate > new Date()) {
|
||||
// entry has a publish date in the future, set global validUntil
|
||||
if (validUntil == null || validUntil > publishDate) {
|
||||
validUntil = publishDate
|
||||
}
|
||||
}
|
||||
})
|
||||
// @ts-ignore
|
||||
context.ssrCacheValidUntil = validUntil
|
||||
}
|
||||
|
||||
// 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,
|
||||
}
|
||||
169
api/hooks/lib/ssr.js
Normal file
169
api/hooks/lib/ssr.js
Normal file
@@ -0,0 +1,169 @@
|
||||
const { apiClientBaseURL } = require("../config-client")
|
||||
|
||||
/**
|
||||
* convert object to string
|
||||
* @param {any} obj object
|
||||
*/
|
||||
function obj2str(obj) {
|
||||
if (Array.isArray(obj)) {
|
||||
return JSON.stringify(
|
||||
obj.map(function (idx) {
|
||||
return obj2str(idx)
|
||||
})
|
||||
)
|
||||
} else if (typeof obj === "object" && obj !== null) {
|
||||
var elements = Object.keys(obj)
|
||||
.sort()
|
||||
.map(function (key) {
|
||||
var val = obj2str(obj[key])
|
||||
if (val) {
|
||||
return key + ":" + val
|
||||
}
|
||||
})
|
||||
|
||||
var elementsCleaned = []
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if (elements[i]) elementsCleaned.push(elements[i])
|
||||
}
|
||||
|
||||
return "{" + elementsCleaned.join("|") + "}"
|
||||
}
|
||||
|
||||
if (obj) return obj
|
||||
}
|
||||
|
||||
// fetch polyfill
|
||||
// [MIT License](LICENSE.md) © [Jason Miller](https://jasonformat.com/)
|
||||
const _f = function (url, options) {
|
||||
if (typeof XMLHttpRequest === "undefined") {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
|
||||
options = options || {}
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest()
|
||||
const keys = []
|
||||
const all = []
|
||||
const headers = {}
|
||||
|
||||
const response = () => ({
|
||||
ok: ((request.status / 100) | 0) == 2, // 200-299
|
||||
statusText: request.statusText,
|
||||
status: request.status,
|
||||
url: request.responseURL,
|
||||
text: () => Promise.resolve(request.responseText),
|
||||
json: () => Promise.resolve(request.responseText).then(JSON.parse),
|
||||
blob: () => Promise.resolve(new Blob([request.response])),
|
||||
clone: response,
|
||||
headers: {
|
||||
// @ts-ignore
|
||||
keys: () => keys,
|
||||
// @ts-ignore
|
||||
entries: () => all,
|
||||
get: (n) => headers[n.toLowerCase()],
|
||||
has: (n) => n.toLowerCase() in headers,
|
||||
},
|
||||
})
|
||||
|
||||
request.open(options.method || "get", url, true)
|
||||
|
||||
request.onload = () => {
|
||||
request
|
||||
.getAllResponseHeaders()
|
||||
// @ts-ignore
|
||||
.replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, (m, key, value) => {
|
||||
keys.push((key = key.toLowerCase()))
|
||||
all.push([key, value])
|
||||
headers[key] = headers[key] ? `${headers[key]},${value}` : value
|
||||
})
|
||||
resolve(response())
|
||||
}
|
||||
|
||||
request.onerror = reject
|
||||
|
||||
request.withCredentials = options.credentials == "include"
|
||||
|
||||
for (const i in options.headers) {
|
||||
request.setRequestHeader(i, options.headers[i])
|
||||
}
|
||||
|
||||
request.send(options.body || null)
|
||||
})
|
||||
}
|
||||
|
||||
const _fetch = typeof fetch === "undefined" ? (typeof window === "undefined" ? _f : window.fetch || _f) : fetch
|
||||
|
||||
/**
|
||||
* api request via client or server
|
||||
* server function ssrRequest is called via context.ssrRequest, binded in ssr hook
|
||||
*
|
||||
* @param {string} endpoint
|
||||
* @param {ApiOptions} options
|
||||
* @returns {Promise<ApiResult>}
|
||||
*/
|
||||
function apiRequest(endpoint, options) {
|
||||
// first check cache if on client
|
||||
const cacheKey = obj2str({ endpoint: endpoint, options: options })
|
||||
|
||||
// @ts-ignore
|
||||
if (typeof window !== "undefined" && window.__SSR_CACHE__) {
|
||||
// @ts-ignore
|
||||
const cache = window.__SSR_CACHE__[cacheKey]
|
||||
console.log("SSR:", cacheKey, cache)
|
||||
if (cache) {
|
||||
return Promise.resolve(cache)
|
||||
}
|
||||
}
|
||||
|
||||
let method = "GET"
|
||||
|
||||
let query = "&count=1"
|
||||
if (options?.filter) query += "&filter=" + encodeURIComponent(JSON.stringify(options.filter))
|
||||
if (options?.sort) query += "&sort=" + options.sort + "&sort=_id"
|
||||
if (options?.limit) query += "&limit=" + options.limit
|
||||
if (options?.offset) query += "&offset=" + options.offset
|
||||
if (options?.projection) query += "&projection=" + options.projection
|
||||
if (options?.lookup) query += "&lookup=" + options.lookup
|
||||
|
||||
if (options?.params) {
|
||||
Object.keys(options.params).forEach((p) => {
|
||||
query += "&" + p + "=" + encodeURIComponent(options.params[p])
|
||||
})
|
||||
}
|
||||
|
||||
let headers = {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
if (options?.headers) headers = { ...headers, ...options.headers }
|
||||
|
||||
if (typeof window === "undefined") {
|
||||
// server
|
||||
|
||||
// reference via context from get hook to tree shake in client
|
||||
// @ts-ignore
|
||||
const d = context.ssrRequest(cacheKey, endpoint, query, Object.assign({}, options, { method, headers }))
|
||||
return d
|
||||
} else {
|
||||
// client
|
||||
let url = endpoint + (query ? "?" + query : "")
|
||||
console.log("fetch", apiClientBaseURL + url)
|
||||
return _fetch(apiClientBaseURL + url, {
|
||||
method,
|
||||
mode: "cors",
|
||||
headers,
|
||||
}).then((response) => {
|
||||
return response?.json().then((json) => {
|
||||
if (response?.status < 200 || response?.status >= 400) {
|
||||
return Promise.reject({ response, data: json })
|
||||
}
|
||||
return Promise.resolve({ data: json || null, count: response.headers?.get("x-results-count") || 0 })
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
obj2str,
|
||||
apiRequest,
|
||||
}
|
||||
@@ -6,38 +6,6 @@ function log(str) {
|
||||
console.log(JSON.stringify(str, undefined, 4))
|
||||
}
|
||||
|
||||
/**
|
||||
* convert object to string
|
||||
* @param {any} obj object
|
||||
*/
|
||||
function obj2str(obj) {
|
||||
if (Array.isArray(obj)) {
|
||||
return JSON.stringify(
|
||||
obj.map(function (idx) {
|
||||
return obj2str(idx)
|
||||
})
|
||||
)
|
||||
} else if (typeof obj === "object" && obj !== null) {
|
||||
var elements = Object.keys(obj)
|
||||
.sort()
|
||||
.map(function (key) {
|
||||
var val = obj2str(obj[key])
|
||||
if (val) {
|
||||
return key + ":" + val
|
||||
}
|
||||
})
|
||||
|
||||
var elementsCleaned = []
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if (elements[i]) elementsCleaned.push(elements[i])
|
||||
}
|
||||
|
||||
return "{" + elementsCleaned.join("|") + "}"
|
||||
}
|
||||
|
||||
if (obj) return obj
|
||||
}
|
||||
|
||||
/**
|
||||
* clear SSR cache
|
||||
*/
|
||||
@@ -49,5 +17,4 @@ function clearSSRCache() {
|
||||
module.exports = {
|
||||
log,
|
||||
clearSSRCache,
|
||||
obj2str,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user