UNPKG

convex

Version:

Client for the Convex Cloud

85 lines (84 loc) 2.5 kB
"use strict"; import { convexToJson, jsonToConvex, version, STATUS_CODE_UDF_FAILED } from "@convex-dev/common"; import { createError, logToConsole } from "./logging.js"; const hasFetch = typeof window !== "undefined" && typeof window.fetch !== "undefined"; const fetch = hasFetch ? window.fetch : (...args) => import("node-fetch").then( ({ default: fetch2 }) => fetch2(...args) ); export class ConvexHttpClient { constructor(clientConfig) { this.address = `${clientConfig.address}/api/${version}`; } backendUrl() { return this.address; } setAuth(value) { this.auth = value; } clearAuth() { this.auth = void 0; } query(name) { return async (...args) => { const argsJSON = JSON.stringify(convexToJson(args)); const argsComponent = encodeURIComponent(argsJSON); const url = `${this.address}/udf?path=${name}&args=${argsComponent}`; const headers = this.auth ? { Authorization: `Bearer ${this.auth}` } : {}; const response = await fetch(url, { credentials: "include", headers }); if (!response.ok && response.status != STATUS_CODE_UDF_FAILED) { throw new Error(await response.text()); } const respJSON = await response.json(); const value = jsonToConvex(respJSON.value); for (const line of respJSON.logs) { logToConsole("info", "query", name, line); } if (!respJSON.success) { throw createError("query", name, value); } return value; }; } mutation(name) { return async (...args) => { const body = JSON.stringify({ path: name, args: convexToJson(args), tokens: [] }); const headers = { "Content-Type": "application/json" }; if (this.auth) { headers["Authorization"] = `Bearer ${this.auth}`; } const response = await fetch(`${this.address}/udf`, { body, method: "POST", headers, credentials: "include" }); if (!response.ok && response.status != STATUS_CODE_UDF_FAILED) { throw new Error(await response.text()); } const respJSON = await response.json(); const value = jsonToConvex(respJSON.value); for (const line of respJSON.logs) { logToConsole("info", "mutation", name, line); } if (!respJSON.success) { throw createError("mutation", name, value); } return value; }; } } //# sourceMappingURL=http_client.js.map