feat: create function to verify client existance in hitphone manager

feat-hitphone-integration
Henrriky 2024-05-08 12:22:50 -03:00
parent bc4efc299d
commit 0b9a5232cd
3 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,32 @@
import { cache } from "./utils/cache";
import authConfig from "../../../config/auth";
import { responseOk } from "./utils/fetch";
export const fetchWithKey: typeof fetch = async (endpoint, options) => {
const response = await fetch(authConfig.hitphone.CLIENT_SERVICE_URL + endpoint, {
...options,
headers: {
...options?.headers,
"X-Api-Key": authConfig.hitphone.CLIENT_SERVICE_API_KEY,
},
});
return response;
};
const CLIENT_EXISTS_CACHE_TTL = 10 * 1000 * 60;
const clientExistsCache = cache<boolean>(CLIENT_EXISTS_CACHE_TTL);
export const clientExists = async (id: string): Promise<boolean> => {
const fetcher = async (id: string) => {
const response = await fetchWithKey(`/clients/${id}`, { method: "HEAD" });
await responseOk(response);
return true;
};
const exists = await clientExistsCache.get(id, () => fetcher(id));
return exists;
};

View File

@ -0,0 +1,35 @@
export const cache = <T>(ttl: number) => {
type Cache = { promise: Promise<T>, timestamp: number };
const store = new Map<string, Cache>();
const get = async (key: string, fetcher: () => Promise<T>) => {
if (store.has(key)) {
const cached = store.get(key)!;
if (Date.now() - cached.timestamp < ttl) {
return cached.promise;
} else {
store.delete(key);
}
}
try {
const promise = fetcher();
store.set(key, {
promise,
timestamp: Date.now()
});
return promise;
} catch (error) {
store.delete(key);
throw error;
}
}
return {
get
};
};

View File

@ -0,0 +1,17 @@
export class FetchClientsApiError extends Error {
public statusCode: number;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
this.name = "FetchClientsApiError";
}
}
export const responseOk = async (response: Response) => {
if (!response.ok) {
const message = await response.text();
throw new FetchClientsApiError(message, response.status);
}
};