feat: create function to verify client existance in hitphone manager
parent
bc4efc299d
commit
0b9a5232cd
|
@ -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;
|
||||
};
|
|
@ -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
|
||||
};
|
||||
};
|
|
@ -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);
|
||||
}
|
||||
};
|
Loading…
Reference in New Issue