@open-condo/miniapp-utils
Version:
A set of helper functions / components / hooks used to build new condo apps fast
47 lines • 1.4 kB
JavaScript
// src/helpers/cookies.ts
import { getCookie } from "cookies-next";
import { createContext, useContext } from "react";
var SSR_COOKIES_DEFAULT_PROP_NAME = "__SSR_COOKIES__";
var SSRCookiesHelper = class {
constructor(allowedCookies, propName) {
this.allowedCookies = allowedCookies;
this.propName = propName || SSR_COOKIES_DEFAULT_PROP_NAME;
this.defaultValues = Object.fromEntries(allowedCookies.map((key) => [key, null]));
this.context = createContext(this.defaultValues);
this.extractSSRCookies = this.extractSSRCookies.bind(this);
}
getContext() {
return this.context;
}
generateUseSSRCookiesExtractorHook() {
const defaultValues = this.defaultValues;
const propName = this.propName;
return function useSSRCookiesExtractor(pageProps) {
return pageProps[propName] || defaultValues;
};
}
generateUseSSRCookiesHook() {
const context = this.context;
return function useSSRCookies() {
return useContext(context);
};
}
extractSSRCookies(req, res, pageParams) {
return {
...pageParams,
props: {
...pageParams.props,
[this.propName]: Object.fromEntries(
Object.keys(this.defaultValues).map((key) => [
key,
getCookie(key, { req, res }) || null
])
)
}
};
}
};
export {
SSRCookiesHelper
};
//# sourceMappingURL=cookies.mjs.map