UNPKG

convex

Version:

Client for the Convex Cloud

80 lines (79 loc) 2.76 kB
"use strict"; import { ConvexHttpClient } from "../browser/index.js"; import { getFunctionName } from "../server/index.js"; import { convexToJson, jsonToConvex } from "../values/index.js"; export async function preloadQuery(query, ...args) { const value = await fetchQuery(query, ...args); const preloaded = { _name: getFunctionName(query), _argsJSON: convexToJson(args[0] ?? {}), _valueJSON: convexToJson(value) }; return preloaded; } export function preloadedQueryResult(preloaded) { return jsonToConvex(preloaded._valueJSON); } export async function fetchQuery(query, ...args) { const [fnArgs, options] = args; const client = setupClient(options ?? {}); return client.query(query, fnArgs); } export async function fetchMutation(mutation, ...args) { const [fnArgs, options] = args; const client = setupClient(options ?? {}); return client.mutation(mutation, fnArgs); } export async function fetchAction(action, ...args) { const [fnArgs, options] = args; const client = setupClient(options ?? {}); return client.action(action, fnArgs); } function setupClient(options) { const client = new ConvexHttpClient( getConvexUrl(options.url, options.skipConvexDeploymentUrlCheck ?? false) ); if (options.token !== void 0) { client.setAuth(options.token); } if (options.adminToken !== void 0) { client.setAdminAuth(options.adminToken); } client.setFetchOptions({ cache: "no-store" }); return client; } function getConvexUrl(deploymentUrl, skipConvexDeploymentUrlCheck) { const url = deploymentUrl ?? process.env.NEXT_PUBLIC_CONVEX_URL; if (!skipConvexDeploymentUrlCheck) { validateDeploymentUrl(url, deploymentUrl === void 0); } return url; } function validateDeploymentUrl(deploymentUrl, isFromEnv) { if (typeof deploymentUrl === "undefined") { throw new Error( isFromEnv ? `Environment variable NEXT_PUBLIC_CONVEX_URL is not set.` : `Convex function called with undefined deployment address.` ); } if (typeof deploymentUrl !== "string") { throw new Error( `Invalid deployment address: found ${deploymentUrl}".` ); } if (!(deploymentUrl.startsWith("http:") || deploymentUrl.startsWith("https:"))) { throw new Error( `Invalid ${isFromEnv ? "NEXT_PUBLIC_CONVEX_URL" : "deployment address"}: Must start with "https://" or "http://". Found "${deploymentUrl}".` ); } if (deploymentUrl.indexOf("127.0.0.1") !== -1 || deploymentUrl.indexOf("localhost") !== -1) { return; } if (!deploymentUrl.endsWith(".convex.cloud")) { throw new Error( `Invalid ${isFromEnv ? "NEXT_PUBLIC_CONVEX_URL" : "deployment address"}: Must end with ".convex.cloud". Found "${deploymentUrl}".` ); } } //# sourceMappingURL=index.js.map