38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import { ConvexHttpClient } from "convex/browser"
|
|
|
|
let client: ConvexHttpClient | null = null
|
|
|
|
/**
|
|
* URL the Next.js server uses to reach Convex. Never derive this from request
|
|
* headers: auth tokens are sent to it, so a forged Host would leak them.
|
|
*/
|
|
export function getConvexServerUrl() {
|
|
return (
|
|
process.env.CONVEX_INTERNAL_URL ??
|
|
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
|
"http://127.0.0.1:3210"
|
|
)
|
|
}
|
|
|
|
export function convexServerOptions(token?: string) {
|
|
return { url: getConvexServerUrl(), token }
|
|
}
|
|
|
|
export function getConvexClient() {
|
|
if (!client) {
|
|
client = new ConvexHttpClient(getConvexServerUrl())
|
|
}
|
|
return client
|
|
}
|
|
|
|
/**
|
|
* Downloads a Convex storage file. The backend builds storage URLs from its
|
|
* public origin, which may not be reachable from here, so the same path is
|
|
* fetched from the internal URL. `null` when it is missing.
|
|
*/
|
|
export async function fetchConvexStorageFile(storageUrl: string) {
|
|
const { pathname, search } = new URL(storageUrl)
|
|
const response = await fetch(new URL(pathname + search, getConvexServerUrl()))
|
|
return response.ok ? Buffer.from(await response.arrayBuffer()) : null
|
|
}
|