-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathutils.ts
80 lines (63 loc) · 1.75 KB
/
utils.ts
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
export function atob(value: string): string {
return Buffer.from(value, 'base64').toString();
}
export function btoa(value: string): string {
return Buffer.from(value).toString('base64');
}
export function encodeByType(type: string, value: any): string | null {
if (value === null) return null;
switch (type) {
case 'date': {
return (value as Date).getTime().toString();
}
case 'number': {
return `${value}`;
}
case 'string': {
return encodeURIComponent(value);
}
default: {
throw new Error(`unknown type in cursor: [${type}]${value}`);
}
}
}
export function decodeByType(type: string, value: string): string | number | Date {
switch (type) {
case 'date': {
const timestamp = parseInt(value, 10);
if (Number.isNaN(timestamp)) {
throw new Error('date column in cursor should be a valid timestamp');
}
return new Date(timestamp);
}
case 'number': {
const num = parseInt(value, 10);
if (Number.isNaN(num)) {
throw new Error('number column in cursor should be a valid number');
}
return num;
}
case 'string': {
return decodeURIComponent(value);
}
default: {
throw new Error(`unknown type in cursor: [${type}]${value}`);
}
}
}
export function stringToBool(value: string): boolean {
return value === 'true';
}
export function stringToNumber(value: string): number {
const result = parseInt(value, 10);
if (Number.isNaN(result)) {
return 0;
}
return result;
}
export function camelOrPascalToUnderscore(str: string): string {
return str.split(/(?=[A-Z])/).join('_').toLowerCase();
}
export function pascalToUnderscore(str: string): string {
return camelOrPascalToUnderscore(str);
}