Turned SDK into a class

This commit is contained in:
DrMint 2024-06-29 10:46:22 +02:00
parent 8727bbcc04
commit bd1cd47dc1
1 changed files with 130 additions and 86 deletions

View File

@ -537,30 +537,17 @@ export type EndpointAllSDKUrls = {
// SDK // SDK
type GetPayloadSDKParams = {
apiURL: string;
email: string;
password: string;
tokenCache?: {
set: (token: string, expirationTimestamp: number) => void;
get: () => string | undefined;
};
responseCache?: {
set: (url: string, response: any) => void;
get: (url: string) => any | undefined;
};
};
const logResponse = (res: Response) => console.log(res.status, res.statusText, res.url);
export const getSDKEndpoint = { export const getSDKEndpoint = {
getConfigEndpoint: () => `/globals/${Collections.WebsiteConfig}/config`, getConfigEndpoint: () => `/globals/${Collections.WebsiteConfig}/config`,
getFolderEndpoint: (slug: string) => `/${Collections.Folders}/slug/${slug}`, getFolderEndpoint: (slug: string) => `/${Collections.Folders}/slug/${slug}`,
getFolderSlugsEndpoint: () => `/${Collections.Folders}/slugs`,
getLanguagesEndpoint: () => `/${Collections.Languages}/all`, getLanguagesEndpoint: () => `/${Collections.Languages}/all`,
getCurrenciesEndpoint: () => `/${Collections.Currencies}/all`, getCurrenciesEndpoint: () => `/${Collections.Currencies}/all`,
getWordingsEndpoint: () => `/${Collections.Wordings}/all`, getWordingsEndpoint: () => `/${Collections.Wordings}/all`,
getPageEndpoint: (slug: string) => `/${Collections.Pages}/slug/${slug}`, getPageEndpoint: (slug: string) => `/${Collections.Pages}/slug/${slug}`,
getPageSlugsEndpoint: () => `/${Collections.Pages}/slugs`,
getCollectibleEndpoint: (slug: string) => `/${Collections.Collectibles}/slug/${slug}`, getCollectibleEndpoint: (slug: string) => `/${Collections.Collectibles}/slug/${slug}`,
getCollectibleSlugsEndpoint: () => `/${Collections.Collectibles}/slugs`,
getCollectibleScansEndpoint: (slug: string) => `/${Collections.Collectibles}/slug/${slug}/scans`, getCollectibleScansEndpoint: (slug: string) => `/${Collections.Collectibles}/slug/${slug}/scans`,
getCollectibleScanPageEndpoint: (slug: string, index: string) => getCollectibleScanPageEndpoint: (slug: string, index: string) =>
`/${Collections.Collectibles}/slug/${slug}/scans/${index}`, `/${Collections.Collectibles}/slug/${slug}/scans/${index}`,
@ -579,21 +566,51 @@ export const getSDKEndpoint = {
getLoginEndpoint: () => `/${Collections.Recorders}/login`, getLoginEndpoint: () => `/${Collections.Recorders}/login`,
}; };
export const getPayloadSDK = ({ type PayloadSDKResponse<T> = {
apiURL, data: T;
email, endpointCalled: string;
password, };
tokenCache,
responseCache, type PayloadTokenCache = {
}: GetPayloadSDKParams) => { set: (token: string, expirationTimestamp: number) => void;
const refreshToken = async () => { get: () => string | undefined;
const loginUrl = `${apiURL}${getSDKEndpoint.getLoginEndpoint()}`; };
type PayloadDataCache = {
set: (url: string, response: any) => void;
get: (url: string) => any | undefined;
};
export class PayloadSDK {
private tokenCache: PayloadTokenCache | undefined;
private dataCache: PayloadDataCache | undefined;
constructor(
private readonly apiURL: string,
private readonly email: string,
private readonly password: string
) {}
addTokenCache(tokenCache: PayloadTokenCache) {
this.tokenCache = tokenCache;
}
addDataCache(dataCache: PayloadDataCache) {
this.dataCache = dataCache;
}
private logResponse(res: Response) {
console.log(res.status, res.statusText, res.url);
}
private async refreshToken() {
const loginUrl = `${this.apiURL}${getSDKEndpoint.getLoginEndpoint()}`;
const loginResult = await fetch(loginUrl, { const loginResult = await fetch(loginUrl, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }), body: JSON.stringify({ email: this.email, password: this.password }),
}); });
logResponse(loginResult); this.logResponse(loginResult);
if (loginResult.status !== 200) { if (loginResult.status !== 200) {
throw new Error("Unable to login"); throw new Error("Unable to login");
@ -603,77 +620,104 @@ export const getPayloadSDK = ({
token: string; token: string;
exp: number; exp: number;
}; };
tokenCache?.set(token, exp); this.tokenCache?.set(token, exp);
return token; return token;
}; }
const request = async (endpoint: string): Promise<any> => { async request<T>(endpoint: string): Promise<PayloadSDKResponse<T>> {
const cachedResponse = responseCache?.get(endpoint); const cachedResponse = this.dataCache?.get(endpoint);
if (cachedResponse) { if (cachedResponse) {
return cachedResponse; return cachedResponse;
} }
const result = await fetch(`${apiURL}${endpoint}`, { const result = await fetch(`${this.apiURL}${endpoint}`, {
headers: { headers: {
Authorization: `JWT ${tokenCache?.get() ?? (await refreshToken())}`, Authorization: `JWT ${this.tokenCache?.get() ?? (await this.refreshToken())}`,
}, },
}); });
logResponse(result); this.logResponse(result);
if (!result.ok) { if (!result.ok) {
throw new Error("Unhandled fetch error"); throw new Error("Unhandled fetch error");
} }
const data = await result.json(); const response = { data: await result.json(), endpointCalled: endpoint };
responseCache?.set(endpoint, data); this.dataCache?.set(endpoint, response);
return data; return response;
}; }
return { async getConfig(): Promise<PayloadSDKResponse<EndpointWebsiteConfig>> {
getConfig: async (): Promise<EndpointWebsiteConfig> => return await this.request(getSDKEndpoint.getConfigEndpoint());
await request(getSDKEndpoint.getConfigEndpoint()), }
getFolder: async (slug: string): Promise<EndpointFolder> => async getFolder(slug: string): Promise<PayloadSDKResponse<EndpointFolder>> {
await request(getSDKEndpoint.getFolderEndpoint(slug)), return await this.request(getSDKEndpoint.getFolderEndpoint(slug));
getLanguages: async (): Promise<Language[]> => }
await request(getSDKEndpoint.getLanguagesEndpoint()), async getFolderSlugs(): Promise<PayloadSDKResponse<string[]>> {
getCurrencies: async (): Promise<Currency[]> => return await this.request(getSDKEndpoint.getFolderSlugsEndpoint());
await request(getSDKEndpoint.getCurrenciesEndpoint()), }
getWordings: async (): Promise<EndpointWording[]> => async getLanguages(): Promise<PayloadSDKResponse<Language[]>> {
await request(getSDKEndpoint.getWordingsEndpoint()), return await this.request(getSDKEndpoint.getLanguagesEndpoint());
getPage: async (slug: string): Promise<EndpointPage> => }
await request(getSDKEndpoint.getPageEndpoint(slug)), async getCurrencies(): Promise<PayloadSDKResponse<Currency[]>> {
getCollectible: async (slug: string): Promise<EndpointCollectible> => return await this.request(getSDKEndpoint.getCurrenciesEndpoint());
await request(getSDKEndpoint.getCollectibleEndpoint(slug)), }
getCollectibleScans: async (slug: string): Promise<EndpointCollectibleScans> => async getWordings(): Promise<PayloadSDKResponse<EndpointWording[]>> {
await request(getSDKEndpoint.getCollectibleScansEndpoint(slug)), return await this.request(getSDKEndpoint.getWordingsEndpoint());
getCollectibleScanPage: async ( }
slug: string, async getPage(slug: string): Promise<PayloadSDKResponse<EndpointPage>> {
index: string return await this.request(getSDKEndpoint.getPageEndpoint(slug));
): Promise<EndpointCollectibleScanPage> => }
await request(getSDKEndpoint.getCollectibleScanPageEndpoint(slug, index)), async getPageSlugs(): Promise<PayloadSDKResponse<string[]>> {
getCollectibleGallery: async (slug: string): Promise<EndpointCollectibleGallery> => return await this.request(getSDKEndpoint.getPageSlugsEndpoint());
await request(getSDKEndpoint.getCollectibleGalleryEndpoint(slug)), }
getCollectibleGalleryImage: async ( async getCollectible(slug: string): Promise<PayloadSDKResponse<EndpointCollectible>> {
slug: string, return await this.request(getSDKEndpoint.getCollectibleEndpoint(slug));
index: string }
): Promise<EndpointCollectibleGalleryImage> => async getCollectibleSlugs(): Promise<PayloadSDKResponse<string[]>> {
await request(getSDKEndpoint.getCollectibleGalleryImageEndpoint(slug, index)), return await this.request(getSDKEndpoint.getCollectibleSlugsEndpoint());
getChronologyEvents: async (): Promise<EndpointChronologyEvent[]> => }
await request(getSDKEndpoint.getChronologyEventsEndpoint()), async getCollectibleScans(slug: string): Promise<PayloadSDKResponse<EndpointCollectibleScans>> {
getChronologyEventByID: async (id: string): Promise<EndpointChronologyEvent> => return await this.request(getSDKEndpoint.getCollectibleScansEndpoint(slug));
await request(getSDKEndpoint.getChronologyEventByIDEndpoint(id)), }
getImageByID: async (id: string): Promise<EndpointImage> => async getCollectibleScanPage(
await request(getSDKEndpoint.getImageByIDEndpoint(id)), slug: string,
getAudioByID: async (id: string): Promise<EndpointAudio> => index: string
await request(getSDKEndpoint.getAudioByIDEndpoint(id)), ): Promise<PayloadSDKResponse<EndpointCollectibleScanPage>> {
getVideoByID: async (id: string): Promise<EndpointVideo> => return await this.request(getSDKEndpoint.getCollectibleScanPageEndpoint(slug, index));
await request(getSDKEndpoint.getVideoByIDEndpoint(id)), }
getFileByID: async (id: string): Promise<EndpointFile> => async getCollectibleGallery(
await request(getSDKEndpoint.getFileByIDEndpoint(id)), slug: string
getRecorderByID: async (id: string): Promise<EndpointRecorder> => ): Promise<PayloadSDKResponse<EndpointCollectibleGallery>> {
await request(getSDKEndpoint.getRecorderByIDEndpoint(id)), return await this.request(getSDKEndpoint.getCollectibleGalleryEndpoint(slug));
getAllSdkUrls: async (): Promise<EndpointAllSDKUrls> => }
await request(getSDKEndpoint.getAllSDKUrlsEndpoint()), async getCollectibleGalleryImage(
request: async (pathname: string): Promise<any> => await request(pathname), slug: string,
}; index: string
}; ): Promise<PayloadSDKResponse<EndpointCollectibleGalleryImage>> {
return await this.request(getSDKEndpoint.getCollectibleGalleryImageEndpoint(slug, index));
}
async getChronologyEvents(): Promise<PayloadSDKResponse<EndpointChronologyEvent[]>> {
return await this.request(getSDKEndpoint.getChronologyEventsEndpoint());
}
async getChronologyEventByID(id: string): Promise<PayloadSDKResponse<EndpointChronologyEvent>> {
return await this.request(getSDKEndpoint.getChronologyEventByIDEndpoint(id));
}
async getImageByID(id: string): Promise<PayloadSDKResponse<EndpointImage>> {
return await this.request(getSDKEndpoint.getImageByIDEndpoint(id));
}
async getAudioByID(id: string): Promise<PayloadSDKResponse<EndpointAudio>> {
return await this.request(getSDKEndpoint.getAudioByIDEndpoint(id));
}
async getVideoByID(id: string): Promise<PayloadSDKResponse<EndpointVideo>> {
return await this.request(getSDKEndpoint.getVideoByIDEndpoint(id));
}
async getFileByID(id: string): Promise<PayloadSDKResponse<EndpointFile>> {
return await this.request(getSDKEndpoint.getFileByIDEndpoint(id));
}
async getRecorderByID(id: string): Promise<PayloadSDKResponse<EndpointRecorder>> {
return await this.request(getSDKEndpoint.getRecorderByIDEndpoint(id));
}
async getAllSdkUrls(): Promise<PayloadSDKResponse<EndpointAllSDKUrls>> {
return await this.request(getSDKEndpoint.getAllSDKUrlsEndpoint());
}
}