2
0
Files
bot/apps/builder/services/utils.ts
Baptiste Arnaud d369b4d941 🦴 Add viewer backbone
2021-12-24 06:39:33 +01:00

94 lines
2.2 KiB
TypeScript

import { Parser } from 'htmlparser2'
export const fetcher = async (input: RequestInfo, init?: RequestInit) => {
const res = await fetch(input, init)
return res.json()
}
export const isMobile =
typeof window !== 'undefined' &&
window.matchMedia('only screen and (max-width: 760px)').matches
export const sendRequest = async <ResponseData>({
url,
method,
body,
}: {
url: string
method: string
body?: Record<string, unknown>
}): Promise<{ data?: ResponseData; error?: Error }> => {
try {
const response = await fetch(url, {
method,
mode: 'cors',
body: body ? JSON.stringify(body) : undefined,
})
if (!response.ok) throw new Error(response.statusText)
const data = await response.json()
return { data }
} catch (e) {
console.error(e)
return { error: e as Error }
}
}
export const insertItemInList = <T>(
arr: T[],
index: number,
newItem: T
): T[] => [...arr.slice(0, index), newItem, ...arr.slice(index)]
export const isDefined = <T>(value: T | undefined | null): value is T => {
return <T>value !== undefined && <T>value !== null
}
export const isNotDefined = <T>(value: T | undefined | null): value is T => {
return <T>value === undefined || <T>value === null
}
export const preventUserFromRefreshing = (e: BeforeUnloadEvent) => {
e.preventDefault()
e.returnValue = ''
}
export const parseHtmlStringToPlainText = (html: string): string => {
let label = ''
const parser = new Parser({
ontext(text) {
label += `${text}`
},
})
parser.write(html)
parser.end()
return label
}
export const toKebabCase = (value: string) => {
const matched = value.match(
/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
)
if (!matched) return ''
return matched.map((x) => x.toLowerCase()).join('-')
}
interface Omit {
// eslint-disable-next-line @typescript-eslint/ban-types
<T extends object, K extends [...(keyof T)[]]>(obj: T, ...keys: K): {
[K2 in Exclude<keyof T, K[number]>]: T[K2]
}
}
export const omit: Omit = (obj, ...keys) => {
const ret = {} as {
[K in keyof typeof obj]: typeof obj[K]
}
let key: keyof typeof obj
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key]
}
}
return ret
}