forked from vercel/ai-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
93 lines (80 loc) · 2.43 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
81
82
83
84
85
86
87
88
89
90
91
92
93
import { clsx, type ClassValue } from 'clsx'
import { customAlphabet } from 'nanoid'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export const nanoid = customAlphabet(
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
7
) // 7-character random string
export async function fetcher<JSON = any>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
const res = await fetch(input, init)
if (!res.ok) {
const json = await res.json()
if (json.error) {
const error = new Error(json.error) as Error & {
status: number
}
error.status = res.status
throw error
} else {
throw new Error('An unexpected error occurred')
}
}
return res.json()
}
export function formatDate(input: string | number | Date): string {
const date = new Date(input)
return date.toLocaleDateString('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric'
})
}
export const formatNumber = (value: number) =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(value)
export const runAsyncFnWithoutBlocking = (
fn: (...args: any) => Promise<any>
) => {
fn().catch(error => {
console.error('An error occurred in the async function:', error);
});
};
export const sleep = (ms: number) =>
new Promise(resolve => setTimeout(resolve, ms))
export const getStringFromBuffer = (buffer: ArrayBuffer) =>
Array.from(new Uint8Array(buffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
export enum ResultCode {
InvalidCredentials = 'INVALID_CREDENTIALS',
InvalidSubmission = 'INVALID_SUBMISSION',
UserAlreadyExists = 'USER_ALREADY_EXISTS',
UnknownError = 'UNKNOWN_ERROR',
UserCreated = 'USER_CREATED',
UserLoggedIn = 'USER_LOGGED_IN'
}
export const getMessageFromCode = (resultCode: string) => {
switch (resultCode) {
case ResultCode.InvalidCredentials:
return 'Invalid credentials!'
case ResultCode.InvalidSubmission:
return 'Invalid submission, please try again!'
case ResultCode.UserAlreadyExists:
return 'User already exists, please log in!'
case ResultCode.UserCreated:
return 'User created, welcome!'
case ResultCode.UnknownError:
return 'Something went wrong, please try again!'
case ResultCode.UserLoggedIn:
return 'Logged in!'
}
}
export const unixTsNow = () => Math.floor(Date.now() / 1000);