chatbot-template/lib/utils.ts

44 lines
1,013 B
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
import { clsx, type ClassValue } from 'clsx'
import { customAlphabet } from 'nanoid'
import { twMerge } from 'tailwind-merge'
2023-05-19 12:33:56 -04:00
export function cn(...inputs: ClassValue[]) {
2023-06-02 15:33:48 -04:00
return twMerge(clsx(inputs))
2023-05-19 12:33:56 -04:00
}
export const nanoid = customAlphabet(
2023-06-02 15:33:48 -04:00
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
2023-05-19 12:33:56 -04:00
7
2023-06-02 15:33:48 -04:00
) // 7-character random string
2023-05-19 12:33:56 -04:00
export async function fetcher<JSON = any>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
2023-06-02 15:33:48 -04:00
const res = await fetch(input, init)
2023-05-19 12:33:56 -04:00
if (!res.ok) {
2023-06-02 15:33:48 -04:00
const json = await res.json()
2023-05-19 12:33:56 -04:00
if (json.error) {
const error = new Error(json.error) as Error & {
2023-06-02 15:33:48 -04:00
status: number
}
error.status = res.status
throw error
2023-05-19 12:33:56 -04:00
} else {
2023-06-02 15:33:48 -04:00
throw new Error('An unexpected error occurred')
2023-05-19 12:33:56 -04:00
}
}
2023-06-02 15:33:48 -04:00
return res.json()
2023-05-19 12:33:56 -04:00
}
2023-06-16 15:20:42 +04:00
export function formatDate(input: string | number | Date): string {
const date = new Date(input)
return date.toLocaleDateString('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric'
})
}