Moved caching responsability to this repo for SDK use
This commit is contained in:
parent
91e67a7645
commit
6f9d2c0578
1
TODO.md
1
TODO.md
|
@ -14,7 +14,6 @@
|
|||
- [Timeline] Error if collectible not published?
|
||||
- [Timeline] display source language
|
||||
- [Timeline] Add details button in footer with credits + last updated / created
|
||||
- [SDK] create a initPayload() that return a payload sdk (and stop hard wirring to ENV or node-cache)
|
||||
- [Videos] see why no video on Firefox and no poster on Chrome https://v3.accords-library.com/en/videos/661b672825d380e548dbb8c8
|
||||
- [Videos] Display platform info + channel page
|
||||
- [Timeline] Handle no JS for footers
|
||||
|
|
|
@ -22,6 +22,7 @@ export default defineConfig({
|
|||
},
|
||||
}),
|
||||
],
|
||||
prefetch: false,
|
||||
// devToolbar: { enabled: false },
|
||||
server: {
|
||||
port: parseInt(ASTRO_PORT ?? "4321"),
|
||||
|
|
|
@ -7,7 +7,7 @@ const sdk = await fetch(`${import.meta.env.PAYLOAD_API_URL}/sdk`);
|
|||
if (!sdk.ok) {
|
||||
console.error("Failed to get the sdk", sdk.status, sdk.statusText);
|
||||
} else {
|
||||
const sdkFile = (await sdk.text()).replaceAll("process.env.", "import.meta.env.");
|
||||
const sdkFile = await sdk.text();
|
||||
writeFileSync(`${PAYLOAD_FOLDER}/payload-sdk.ts`, sdkFile, {
|
||||
encoding: "utf-8",
|
||||
});
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { writeFileSync } from "fs";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
|
||||
const TRANSLATION_FOLDER = `${process.cwd()}/src/i18n`;
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import Button from "components/Button.astro";
|
||||
import Tooltip from "components/Tooltip.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import { formatCurrency } from "src/utils/currencies";
|
||||
|
||||
interface Props {
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import Button from "components/Button.astro";
|
||||
import Tooltip from "components/Tooltip.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import { formatLocale } from "src/utils/format";
|
||||
|
||||
interface Props {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
---
|
||||
---
|
||||
import { Icon } from "astro-icon/components";
|
||||
import type { Attribute } from "src/utils/attributes";
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import type { WordingKey } from "src/i18n/wordings-keys";
|
||||
import type { ChronologyEvent, EndpointSource } from "src/shared/payload/payload-sdk";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import { capitalize, formatInlineTitle } from "src/utils/format";
|
||||
|
||||
export const defaultLocale = "en";
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { defineMiddleware, sequence } from "astro:middleware";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import acceptLanguage from "accept-language";
|
||||
import type { AstroCookies } from "astro";
|
||||
import { z } from "astro:content";
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
---
|
||||
import CategoryCard from "./CategoryCard.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
|
||||
const { getLocalizedUrl, getLocalizedMatch } = await getI18n(Astro.locals.currentLocale);
|
||||
---
|
||||
|
|
|
@ -5,7 +5,7 @@ import {
|
|||
refreshLocales,
|
||||
refreshWordings,
|
||||
refreshWebsiteConfig,
|
||||
} from "src/utils/cachedPayload";
|
||||
} from "src/utils/payload";
|
||||
|
||||
const auth = Astro.request.headers.get("Authorization");
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
import RichText from "components/RichText/RichText.astro";
|
||||
import { payload, type EndpointPage } from "src/shared/payload/payload-sdk";
|
||||
import type { EndpointPage } from "src/shared/payload/payload-sdk";
|
||||
import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro";
|
||||
import MasoTarget from "components/Maso/MasoTarget.astro";
|
||||
import TableOfContent from "components/TableOfContent/TableOfContent.astro";
|
||||
|
@ -11,6 +11,7 @@ import AsideLayout from "components/AppLayout/AsideLayout.astro";
|
|||
import AppLayoutDescription from "components/AppLayout/components/AppLayoutDescription.astro";
|
||||
import Attributes from "components/Attributes.astro";
|
||||
import type { Attribute } from "src/utils/attributes";
|
||||
import { payload } from "src/utils/payload";
|
||||
|
||||
export const partial = true;
|
||||
|
||||
|
|
|
@ -5,7 +5,8 @@ import TimelineLanguageOverride from "pages/[locale]/timeline/_components/Timeli
|
|||
import TimelineNote from "pages/[locale]/timeline/_components/TimelineNote.astro";
|
||||
import TimelineSourcesButton from "pages/[locale]/timeline/_components/TimelineSourcesButton.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload, type EndpointChronologyEvent } from "src/shared/payload/payload-sdk";
|
||||
import type { EndpointChronologyEvent } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
|
||||
export const partial = true;
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ import Credits from "components/Credits.astro";
|
|||
import DownloadButton from "components/DownloadButton.astro";
|
||||
import RichText from "components/RichText/RichText.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import Lightbox from "components/Lightbox.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ import AppLayout from "components/AppLayout/AppLayout.astro";
|
|||
import AppLayoutDescription from "components/AppLayout/components/AppLayoutDescription.astro";
|
||||
import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
@ -75,6 +75,7 @@ const translation = getLocalizedMatch(translations);
|
|||
height: auto;
|
||||
width: auto;
|
||||
box-shadow: 0 5px 20px -10px var(--color-shadow);
|
||||
border-radius: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { CollectibleNature, payload } from "src/shared/payload/payload-sdk";
|
||||
import { CollectibleNature } from "src/shared/payload/payload-sdk";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
import ImageTile from "./_components/ImageTile.astro";
|
||||
import SizeInfo from "./_components/SizeInfo.astro";
|
||||
|
@ -17,6 +17,7 @@ import AppLayoutDescription from "components/AppLayout/components/AppLayoutDescr
|
|||
import { convert } from "src/utils/currencies";
|
||||
import Attributes from "components/Attributes.astro";
|
||||
import type { Attribute } from "src/utils/attributes";
|
||||
import { payload } from "src/utils/payload";
|
||||
|
||||
const { slug } = Astro.params;
|
||||
const { getLocalizedMatch, getLocalizedUrl, t, formatDate, formatPrice } = await getI18n(
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import Lightbox from "components/Lightbox.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ import AppLayout from "components/AppLayout/AppLayout.astro";
|
|||
import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro";
|
||||
import Credits from "components/Credits.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
import ScanPreview from "./_components/ScanPreview.astro";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
import { Collections, payload } from "src/shared/payload/payload-sdk";
|
||||
import { Collections } from "src/shared/payload/payload-sdk";
|
||||
import FoldersSection from "./_components/FoldersSection.astro";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
import ErrorMessage from "components/ErrorMessage.astro";
|
||||
|
@ -13,6 +13,7 @@ import VideoPreview from "components/Previews/VideoPreview.astro";
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro";
|
||||
import AppLayoutDescription from "components/AppLayout/components/AppLayoutDescription.astro";
|
||||
import { payload } from "src/utils/payload";
|
||||
|
||||
const { slug } = Astro.params;
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import Lightbox from "components/Lightbox.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@ import LibraryGrid from "./_components/LibraryGrid.astro";
|
|||
import ChronicleCard from "./_components/ChronicleCard.astro";
|
||||
import LinkCard from "./_components/LinkCard.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import AppLayoutDescription from "components/AppLayout/components/AppLayoutDescription.astro";
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import Page from "src/pages/[locale]/api/pages/partial.astro";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@ import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro
|
|||
import Attributes from "components/Attributes.astro";
|
||||
import RichText from "components/RichText/RichText.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import type { Attribute } from "src/utils/attributes";
|
||||
import { formatLocale } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import { formatCurrency } from "src/utils/currencies";
|
||||
import { formatLocale } from "src/utils/format";
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import type { EndpointChronologyEvent } from "src/shared/payload/payload-sdk";
|
||||
import TimelineEvent from "./TimelineEvent.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
|
||||
interface Props {
|
||||
year: number;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { groupBy } from "src/utils/array";
|
||||
import TimelineYear from "./_components/TimelineYear.astro";
|
||||
import AppLayout from "components/AppLayout/AppLayout.astro";
|
||||
|
@ -7,7 +7,7 @@ import AppLayoutTitle from "components/AppLayout/components/AppLayoutTitle.astro
|
|||
import Card from "components/Card.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import AppLayoutBackgroundImg from "components/AppLayout/components/AppLayoutBackgroundImg.astro";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
import type { WordingKey } from "src/i18n/wordings-keys";
|
||||
import AppLayoutDescription from "components/AppLayout/components/AppLayoutDescription.astro";
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ import DownloadButton from "components/DownloadButton.astro";
|
|||
import RichText from "components/RichText/RichText.astro";
|
||||
import VideoPlayer from "components/VideoPlayer.astro";
|
||||
import { getI18n } from "src/i18n/i18n";
|
||||
import { payload } from "src/shared/payload/payload-sdk";
|
||||
import { payload } from "src/utils/payload";
|
||||
import { formatInlineTitle, formatRichTextToString } from "src/utils/format";
|
||||
import { fetchOr404 } from "src/utils/responses";
|
||||
|
||||
|
|
|
@ -1349,86 +1349,6 @@ export const isBlockLineBlock = (block: GenericBlock): block is LineBlock =>
|
|||
|
||||
////////////////// SDK //////////////////
|
||||
|
||||
import NodeCache from "node-cache";
|
||||
|
||||
|
||||
const REFRESH_FREQUENCY_IN_SEC = 60;
|
||||
const CACHE = new NodeCache({
|
||||
checkperiod: REFRESH_FREQUENCY_IN_SEC,
|
||||
deleteOnExpire: true,
|
||||
forceString: true,
|
||||
maxKeys: 1,
|
||||
});
|
||||
const TOKEN_KEY = "token";
|
||||
|
||||
type PayloadLoginResponse = {
|
||||
token: string;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
const refreshToken = async () => {
|
||||
const loginUrl = payloadApiUrl(Collections.Recorders, "login");
|
||||
const loginResult = await fetch(loginUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: import.meta.env.PAYLOAD_USER,
|
||||
password: import.meta.env.PAYLOAD_PASSWORD,
|
||||
}),
|
||||
});
|
||||
logResponse(loginResult);
|
||||
|
||||
if (loginResult.status !== 200) {
|
||||
throw new Error("Unable to login");
|
||||
}
|
||||
|
||||
const loginJson = (await loginResult.json()) as PayloadLoginResponse;
|
||||
const { token, exp } = loginJson;
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const ttl = Math.floor(exp - now - REFRESH_FREQUENCY_IN_SEC * 2);
|
||||
const ttlInMinutes = Math.floor(ttl / 60);
|
||||
console.log("Token was refreshed. TTL is", ttlInMinutes, "minutes.");
|
||||
CACHE.set(TOKEN_KEY, token, ttl);
|
||||
return token;
|
||||
};
|
||||
|
||||
const getToken = async (): Promise<string> => {
|
||||
const cachedToken = CACHE.get<string>(TOKEN_KEY);
|
||||
if (cachedToken !== undefined) {
|
||||
const cachedTokenTtl = CACHE.getTtl(TOKEN_KEY) as number;
|
||||
const diffInMinutes = Math.floor((cachedTokenTtl - Date.now()) / 1000 / 60);
|
||||
console.log("Retrieved token from cache. TTL is", diffInMinutes, "minutes.");
|
||||
return cachedToken;
|
||||
}
|
||||
console.log("Refreshing token");
|
||||
return await refreshToken();
|
||||
};
|
||||
|
||||
const injectAuth = async (init?: RequestInit): Promise<RequestInit> => ({
|
||||
...init,
|
||||
headers: {
|
||||
...init?.headers,
|
||||
Authorization: `JWT ${await getToken()}`,
|
||||
},
|
||||
});
|
||||
|
||||
const logResponse = (res: Response) => console.log(res.status, res.statusText, res.url);
|
||||
|
||||
const payloadApiUrl = (collection: Collections, endpoint?: string, isGlobal?: boolean): string =>
|
||||
`${import.meta.env.PAYLOAD_API_URL}/${isGlobal === undefined ? "" : "globals/"}${collection}${endpoint === undefined ? "" : `/${endpoint}`}`;
|
||||
|
||||
const request = async (url: string, init?: RequestInit): Promise<Response> => {
|
||||
const result = await fetch(url, await injectAuth(init));
|
||||
logResponse(result);
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error("Unhandled fetch error");
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// SDK and Types
|
||||
|
||||
export type EndpointFolder = {
|
||||
slug: string;
|
||||
|
@ -1868,49 +1788,106 @@ export type PayloadImage = PayloadMedia & {
|
|||
height: number;
|
||||
};
|
||||
|
||||
export const payload = {
|
||||
getConfig: async (): Promise<EndpointWebsiteConfig> =>
|
||||
await (await request(payloadApiUrl(Collections.WebsiteConfig, `config`, true))).json(),
|
||||
getFolder: async (slug: string): Promise<EndpointFolder> =>
|
||||
await (await request(payloadApiUrl(Collections.Folders, `slug/${slug}`))).json(),
|
||||
getLanguages: async (): Promise<Language[]> =>
|
||||
await (await request(payloadApiUrl(Collections.Languages, `all`))).json(),
|
||||
getCurrencies: async (): Promise<Currency[]> =>
|
||||
await (await request(payloadApiUrl(Collections.Currencies, `all`))).json(),
|
||||
getWordings: async (): Promise<EndpointWording[]> =>
|
||||
await (await request(payloadApiUrl(Collections.Wordings, `all`))).json(),
|
||||
getPage: async (slug: string): Promise<EndpointPage> =>
|
||||
await (await request(payloadApiUrl(Collections.Pages, `slug/${slug}`))).json(),
|
||||
getCollectible: async (slug: string): Promise<EndpointCollectible> =>
|
||||
await (await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}`))).json(),
|
||||
getCollectibleScans: async (slug: string): Promise<EndpointCollectibleScans> =>
|
||||
await (await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/scans`))).json(),
|
||||
getCollectibleScanPage: async (
|
||||
slug: string,
|
||||
index: string
|
||||
): Promise<EndpointCollectibleScanPage> =>
|
||||
await (
|
||||
await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/scans/${index}`))
|
||||
).json(),
|
||||
getCollectibleGallery: async (slug: string): Promise<EndpointCollectibleGallery> =>
|
||||
await (await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/gallery`))).json(),
|
||||
getCollectibleGalleryImage: async (
|
||||
slug: string,
|
||||
index: string
|
||||
): Promise<EndpointCollectibleGalleryImage> =>
|
||||
await (
|
||||
await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/gallery/${index}`))
|
||||
).json(),
|
||||
getChronologyEvents: async (): Promise<EndpointChronologyEvent[]> =>
|
||||
await (await request(payloadApiUrl(Collections.ChronologyEvents, `all`))).json(),
|
||||
getChronologyEventByID: async (id: string): Promise<EndpointChronologyEvent> =>
|
||||
await (await request(payloadApiUrl(Collections.ChronologyEvents, `id/${id}`))).json(),
|
||||
getImageByID: async (id: string): Promise<EndpointImage> =>
|
||||
await (await request(payloadApiUrl(Collections.Images, `id/${id}`))).json(),
|
||||
getAudioByID: async (id: string): Promise<EndpointAudio> =>
|
||||
await (await request(payloadApiUrl(Collections.Audios, `id/${id}`))).json(),
|
||||
getVideoByID: async (id: string): Promise<EndpointVideo> =>
|
||||
await (await request(payloadApiUrl(Collections.Videos, `id/${id}`))).json(),
|
||||
getRecorderByID: async (id: string): Promise<EndpointRecorder> =>
|
||||
await (await request(payloadApiUrl(Collections.Recorders, `id/${id}`))).json(),
|
||||
// SDK
|
||||
|
||||
type GetPayloadSDKParams = {
|
||||
apiURL: string;
|
||||
email: string;
|
||||
password: string;
|
||||
cache: Cache;
|
||||
};
|
||||
|
||||
type Cache = {
|
||||
set: (token: string, expirationTimestamp: number) => void;
|
||||
get: () => string | undefined;
|
||||
};
|
||||
|
||||
const logResponse = (res: Response) => console.log(res.status, res.statusText, res.url);
|
||||
|
||||
export const getPayloadSDK = ({ apiURL, email, password, cache }: GetPayloadSDKParams) => {
|
||||
const refreshToken = async () => {
|
||||
const loginUrl = payloadApiUrl(Collections.Recorders, "login");
|
||||
const loginResult = await fetch(loginUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
logResponse(loginResult);
|
||||
|
||||
if (loginResult.status !== 200) {
|
||||
throw new Error("Unable to login");
|
||||
}
|
||||
|
||||
const { token, exp } = (await loginResult.json()) as {
|
||||
token: string;
|
||||
exp: number;
|
||||
};
|
||||
cache.set(token, exp);
|
||||
return token;
|
||||
};
|
||||
|
||||
const payloadApiUrl = (collection: Collections, endpoint?: string, isGlobal?: boolean): string =>
|
||||
`${apiURL}/${isGlobal === undefined ? "" : "globals/"}${collection}${endpoint === undefined ? "" : `/${endpoint}`}`;
|
||||
|
||||
const request = async (url: string): Promise<Response> => {
|
||||
const result = await fetch(url, {
|
||||
headers: {
|
||||
Authorization: `JWT ${cache.get() ?? (await refreshToken())}`,
|
||||
},
|
||||
});
|
||||
logResponse(result);
|
||||
|
||||
if (result.status !== 200) {
|
||||
throw new Error("Unhandled fetch error");
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
return {
|
||||
getConfig: async (): Promise<EndpointWebsiteConfig> =>
|
||||
await (await request(payloadApiUrl(Collections.WebsiteConfig, `config`, true))).json(),
|
||||
getFolder: async (slug: string): Promise<EndpointFolder> =>
|
||||
await (await request(payloadApiUrl(Collections.Folders, `slug/${slug}`))).json(),
|
||||
getLanguages: async (): Promise<Language[]> =>
|
||||
await (await request(payloadApiUrl(Collections.Languages, `all`))).json(),
|
||||
getCurrencies: async (): Promise<Currency[]> =>
|
||||
await (await request(payloadApiUrl(Collections.Currencies, `all`))).json(),
|
||||
getWordings: async (): Promise<EndpointWording[]> =>
|
||||
await (await request(payloadApiUrl(Collections.Wordings, `all`))).json(),
|
||||
getPage: async (slug: string): Promise<EndpointPage> =>
|
||||
await (await request(payloadApiUrl(Collections.Pages, `slug/${slug}`))).json(),
|
||||
getCollectible: async (slug: string): Promise<EndpointCollectible> =>
|
||||
await (await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}`))).json(),
|
||||
getCollectibleScans: async (slug: string): Promise<EndpointCollectibleScans> =>
|
||||
await (await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/scans`))).json(),
|
||||
getCollectibleScanPage: async (
|
||||
slug: string,
|
||||
index: string
|
||||
): Promise<EndpointCollectibleScanPage> =>
|
||||
await (
|
||||
await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/scans/${index}`))
|
||||
).json(),
|
||||
getCollectibleGallery: async (slug: string): Promise<EndpointCollectibleGallery> =>
|
||||
await (await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/gallery`))).json(),
|
||||
getCollectibleGalleryImage: async (
|
||||
slug: string,
|
||||
index: string
|
||||
): Promise<EndpointCollectibleGalleryImage> =>
|
||||
await (
|
||||
await request(payloadApiUrl(Collections.Collectibles, `slug/${slug}/gallery/${index}`))
|
||||
).json(),
|
||||
getChronologyEvents: async (): Promise<EndpointChronologyEvent[]> =>
|
||||
await (await request(payloadApiUrl(Collections.ChronologyEvents, `all`))).json(),
|
||||
getChronologyEventByID: async (id: string): Promise<EndpointChronologyEvent> =>
|
||||
await (await request(payloadApiUrl(Collections.ChronologyEvents, `id/${id}`))).json(),
|
||||
getImageByID: async (id: string): Promise<EndpointImage> =>
|
||||
await (await request(payloadApiUrl(Collections.Images, `id/${id}`))).json(),
|
||||
getAudioByID: async (id: string): Promise<EndpointAudio> =>
|
||||
await (await request(payloadApiUrl(Collections.Audios, `id/${id}`))).json(),
|
||||
getVideoByID: async (id: string): Promise<EndpointVideo> =>
|
||||
await (await request(payloadApiUrl(Collections.Videos, `id/${id}`))).json(),
|
||||
getRecorderByID: async (id: string): Promise<EndpointRecorder> =>
|
||||
await (await request(payloadApiUrl(Collections.Recorders, `id/${id}`))).json(),
|
||||
};
|
||||
};
|
||||
|
|
|
@ -1,38 +0,0 @@
|
|||
import {
|
||||
payload,
|
||||
type Language,
|
||||
type EndpointWording,
|
||||
type EndpointWebsiteConfig,
|
||||
} from "src/shared/payload/payload-sdk";
|
||||
|
||||
type Cache = {
|
||||
locales: Language[];
|
||||
currencies: string[];
|
||||
wordings: EndpointWording[];
|
||||
config: EndpointWebsiteConfig;
|
||||
};
|
||||
|
||||
const fetchNewData = async (): Promise<Cache> => ({
|
||||
locales: await payload.getLanguages(),
|
||||
currencies: (await payload.getCurrencies()).map(({ id }) => id),
|
||||
wordings: await payload.getWordings(),
|
||||
config: await payload.getConfig(),
|
||||
});
|
||||
|
||||
export let cache = await fetchNewData();
|
||||
|
||||
export const refreshWordings = async () => {
|
||||
cache.wordings = await payload.getWordings();
|
||||
};
|
||||
|
||||
export const refreshCurrencies = async () => {
|
||||
cache.currencies = (await payload.getCurrencies()).map(({ id }) => id);
|
||||
};
|
||||
|
||||
export const refreshLocales = async () => {
|
||||
cache.locales = await payload.getLanguages();
|
||||
};
|
||||
|
||||
export const refreshWebsiteConfig = async () => {
|
||||
cache.config = await payload.getConfig();
|
||||
};
|
|
@ -6,7 +6,7 @@ import {
|
|||
type RichTextContent,
|
||||
type RichTextNode,
|
||||
} from "src/shared/payload/payload-sdk";
|
||||
import { cache } from "src/utils/cachedPayload";
|
||||
import { cache } from "src/utils/payload";
|
||||
|
||||
export const formatLocale = (code: string): string =>
|
||||
cache.locales.find(({ id }) => id === code)?.name ?? code;
|
||||
|
|
|
@ -0,0 +1,74 @@
|
|||
import {
|
||||
type Language,
|
||||
type EndpointWording,
|
||||
type EndpointWebsiteConfig,
|
||||
} from "src/shared/payload/payload-sdk";
|
||||
import { getPayloadSDK } from "src/shared/payload/payload-sdk";
|
||||
import NodeCache from "node-cache";
|
||||
|
||||
const REFRESH_FREQUENCY_IN_SEC = 60;
|
||||
const nodeCache = new NodeCache({
|
||||
checkperiod: REFRESH_FREQUENCY_IN_SEC,
|
||||
deleteOnExpire: true,
|
||||
forceString: true,
|
||||
maxKeys: 1,
|
||||
});
|
||||
const TOKEN_KEY = "token";
|
||||
|
||||
export const payload = getPayloadSDK({
|
||||
apiURL: import.meta.env.PAYLOAD_API_URL,
|
||||
email: import.meta.env.PAYLOAD_USER,
|
||||
password: import.meta.env.PAYLOAD_PASSWORD,
|
||||
cache: {
|
||||
get: () => {
|
||||
const cachedToken = nodeCache.get<string>(TOKEN_KEY);
|
||||
if (cachedToken !== undefined) {
|
||||
const cachedTokenTtl = nodeCache.getTtl(TOKEN_KEY) as number;
|
||||
const diffInMinutes = Math.floor((cachedTokenTtl - Date.now()) / 1000 / 60);
|
||||
console.log("Retrieved token from cache. TTL is", diffInMinutes, "minutes.");
|
||||
return cachedToken;
|
||||
}
|
||||
console.log("No token to be retrieved or the token expired");
|
||||
return undefined;
|
||||
},
|
||||
set: (token, exp) => {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const ttl = Math.floor(exp - now - REFRESH_FREQUENCY_IN_SEC * 2);
|
||||
const ttlInMinutes = Math.floor(ttl / 60);
|
||||
console.log("Token was refreshed. TTL is", ttlInMinutes, "minutes.");
|
||||
nodeCache.set(TOKEN_KEY, token, ttl);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
type Cache = {
|
||||
locales: Language[];
|
||||
currencies: string[];
|
||||
wordings: EndpointWording[];
|
||||
config: EndpointWebsiteConfig;
|
||||
};
|
||||
|
||||
const fetchNewData = async (): Promise<Cache> => ({
|
||||
locales: await payload.getLanguages(),
|
||||
currencies: (await payload.getCurrencies()).map(({ id }) => id),
|
||||
wordings: await payload.getWordings(),
|
||||
config: await payload.getConfig(),
|
||||
});
|
||||
|
||||
export let cache = await fetchNewData();
|
||||
|
||||
export const refreshWordings = async () => {
|
||||
cache.wordings = await payload.getWordings();
|
||||
};
|
||||
|
||||
export const refreshCurrencies = async () => {
|
||||
cache.currencies = (await payload.getCurrencies()).map(({ id }) => id);
|
||||
};
|
||||
|
||||
export const refreshLocales = async () => {
|
||||
cache.locales = await payload.getLanguages();
|
||||
};
|
||||
|
||||
export const refreshWebsiteConfig = async () => {
|
||||
cache.config = await payload.getConfig();
|
||||
};
|
Loading…
Reference in New Issue