47 lines
869 B
TypeScript
47 lines
869 B
TypeScript
import type { ITheme } from '~/server/theme'
|
|
|
|
export const THEME: ITheme = JSON.parse(process.env.THEME!)
|
|
|
|
export const api = async (
|
|
url: string,
|
|
opts: RequestInit & {
|
|
params?: Record<string, any>
|
|
} = {}
|
|
) => {
|
|
if (!url.startsWith('/api')) {
|
|
return {
|
|
error: {
|
|
message: 'malformed API route',
|
|
},
|
|
}
|
|
}
|
|
|
|
const baseURL = new URL(
|
|
typeof location !== 'undefined'
|
|
? location.origin
|
|
: `http://localhost:${process.env.PORT}`
|
|
)
|
|
baseURL.pathname = url
|
|
Object.entries(opts.params || {}).map(([k, v]) => {
|
|
if (v) {
|
|
baseURL.searchParams.set(k, v)
|
|
}
|
|
})
|
|
|
|
const r = await fetch(baseURL.href, opts)
|
|
|
|
try {
|
|
/**
|
|
* Does not rely on `r.ok`, but rather, errorhandler
|
|
*/
|
|
return r.json()
|
|
} catch (_) {}
|
|
|
|
return {
|
|
error: {
|
|
statusCode: r.status,
|
|
message: r,
|
|
},
|
|
}
|
|
}
|