forked from hyperdxio/hyperdx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.ts
More file actions
82 lines (72 loc) · 2.39 KB
/
common.ts
File metadata and controls
82 lines (72 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Granularity } from '@hyperdx/common-utils/dist/core/utils';
export type JSONBlob = Record<string, Json>;
export type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
export const useTry = <T>(fn: () => T): [null | Error | unknown, null | T] => {
let output: null | T = null;
let error: null | Error | unknown = null;
try {
output = fn();
return [error, output];
} catch (e) {
error = e;
return [error, output];
}
};
export const tryJSONStringify = (json: Json) => {
const [_, result] = useTry<string>(() => JSON.stringify(json));
return result;
};
export function parseJSON<T = unknown>(raw: string, label: string): T {
try {
return JSON.parse(raw) as T;
} catch (e) {
throw new Error(`${label} is not valid JSON: ${(e as Error).message}`);
}
}
export const truncateString = (str: string, length: number) => {
if (str.length > length) {
return str.substring(0, length) + '...';
}
return str;
};
export const sleep = (ms: number) =>
new Promise(resolve => setTimeout(resolve, ms));
export const convertMsToGranularityString = (ms: number): Granularity => {
const granularitySizeSeconds = Math.ceil(ms / 1000);
if (granularitySizeSeconds <= 30) {
return Granularity.ThirtySecond;
} else if (granularitySizeSeconds <= 60) {
return Granularity.OneMinute;
} else if (granularitySizeSeconds <= 5 * 60) {
return Granularity.FiveMinute;
} else if (granularitySizeSeconds <= 10 * 60) {
return Granularity.TenMinute;
} else if (granularitySizeSeconds <= 15 * 60) {
return Granularity.FifteenMinute;
} else if (granularitySizeSeconds <= 30 * 60) {
return Granularity.ThirtyMinute;
} else if (granularitySizeSeconds <= 3600) {
return Granularity.OneHour;
} else if (granularitySizeSeconds <= 2 * 3600) {
return Granularity.TwoHour;
} else if (granularitySizeSeconds <= 6 * 3600) {
return Granularity.SixHour;
} else if (granularitySizeSeconds <= 12 * 3600) {
return Granularity.TwelveHour;
} else if (granularitySizeSeconds <= 24 * 3600) {
return Granularity.OneDay;
} else if (granularitySizeSeconds <= 2 * 24 * 3600) {
return Granularity.TwoDay;
} else if (granularitySizeSeconds <= 7 * 24 * 3600) {
return Granularity.SevenDay;
} else if (granularitySizeSeconds <= 30 * 24 * 3600) {
return Granularity.ThirtyDay;
}
return Granularity.ThirtyDay;
};