You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.5 KiB
53 lines
1.5 KiB
|
|
import { sub, format, fromUnixTime } from 'date-fns';
|
|
interface APIResponse<T> {
|
|
success?: boolean
|
|
payload?: T[]
|
|
error?: string
|
|
|
|
}
|
|
|
|
const api_host = process.env.API_HOST;
|
|
|
|
export const fromUnixTimeSafe = (value: string = ""): Date => {
|
|
const n = Number(value);
|
|
if (!n || isNaN(n)) {
|
|
return null;
|
|
}
|
|
|
|
return fromUnixTime(n);
|
|
};
|
|
|
|
export const createSearchDate = (start: Date = new Date(), hours: number = 0): Date => {
|
|
const d = sub(start, { hours });
|
|
d.setSeconds(0);
|
|
return d;
|
|
}
|
|
export const buildQueryParams = (qps = null) => qps == null ? "" : `?${Object.keys(qps).filter(key => !!qps[key] && (qps[key] !== "undefined")).map(key => `${key}=${qps[key]}`).join('&')}`
|
|
export const API_HOST = (url = "", queryParams) => `${api_host}/api/v1/${url}${buildQueryParams(queryParams)}`;
|
|
|
|
export const apiCall = async function <T>(url: string, method: string = 'GET', queryParams = null): Promise<APIResponse<T>> {
|
|
try {
|
|
const data = await fetch(API_HOST(url, queryParams), {
|
|
headers: { "Accept": "application/json" },
|
|
method,
|
|
});
|
|
|
|
const { success, payload } = await data.json();
|
|
|
|
if (success) {
|
|
return { payload };
|
|
}
|
|
|
|
return { error: payload };
|
|
|
|
} catch (error) {
|
|
console.trace(`API CALL FAILED - ${url}: ${error}`);
|
|
return { error };
|
|
}
|
|
}
|
|
|
|
|
|
export const SearchDateFormatStr = "yyyy-MM-dd HH:mm:ss";
|
|
export const formatDateForSearch = date => format(date, SearchDateFormatStr);
|