UNPKG

@nhost/nhost-js

Version:

Nhost JavaScript SDK

357 lines (356 loc) 11.3 kB
var p = Object.defineProperty; var T = (e, t, s) => t in e ? p(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s; var a = (e, t, s) => T(e, typeof t != "symbol" ? t + "" : t, s); import { HasuraAuthClient as m } from "@nhost/hasura-auth-js"; export * from "@nhost/hasura-auth-js"; import { HasuraStorageClient as w } from "@nhost/hasura-storage-js"; export * from "@nhost/hasura-storage-js"; import k from "isomorphic-unfetch"; import { NhostGraphqlClient as b } from "@nhost/graphql-js"; const A = /^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/; function f(e, t) { const { subdomain: s, region: o } = e; if (!s) throw new Error("A `subdomain` must be set."); const c = s.match(A); if (c != null && c.groups) { const { protocol: l, host: i, port: h } = c.groups, r = x(t); return r || (i === "localhost" ? (console.warn( 'The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.' ), `${l || "http"}://localhost:${h || 1337}/v1/${t}`) : h ? `${l || "https"}://local.${t}.local.nhost.run:${h}/v1` : `${l || "https"}://local.${t}.local.nhost.run/v1`); } if (!o) throw new Error('`region` must be set when using a `subdomain` other than "local".'); return `https://${s}.${t}.${o}.nhost.run/v1`; } function S() { return typeof window != "undefined"; } function H() { return typeof process != "undefined" && process.env; } function x(e) { return S() || !H() ? null : process.env[`NHOST_${e.toUpperCase()}_URL`]; } function U(e, t) { const o = t.startsWith("/") ? t : `/${t}`; return e + o; } function $(e) { const t = "subdomain" in e ? f(e, "auth") : e.authUrl, { subdomain: s, region: o } = e; if (!t) throw new Error("Please provide `subdomain` or `authUrl`."); return new m({ url: t, broadcastKey: `${s}${o != null ? o : "local"}`, ...e }); } function v(e) { const t = "subdomain" in e ? f(e, "functions") : e.functionsUrl; if (!t) throw new Error("Please provide `subdomain` or `functionsUrl`."); return new C({ url: t, ...e }); } class C { constructor(t) { a(this, "url"); a(this, "accessToken"); a(this, "adminSecret"); a(this, "headers", {}); const { url: s, adminSecret: o } = t; this.url = s, this.accessToken = null, this.adminSecret = o; } /** * Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic * types to specify the expected response data, request body and error message. * * @example * ### Without generic types * ```ts * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' }) * ``` * * @example * ### Using generic types * ```ts * type Data = { * message: string * } * * type Body = { * email: string * name: string * } * * type ErrorMessage = { * details: string * } * * // The function will only accept a body of type `Body` * const { res, error } = await nhost.functions.call<Data, Body, ErrorMessage>( * 'send-welcome-email', * { email: 'joe@example.com', name: 'Joe Doe' } * ) * * // Now the response data is typed as `Data` * console.log(res?.data.message) * * // Now the error message is typed as `ErrorMessage` * console.log(error?.message.details) * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call */ async call(t, s, o) { var i, h; const c = { "Content-Type": "application/json", ...this.generateAccessTokenHeaders(), ...o == null ? void 0 : o.headers, ...this.headers // nhost functions client headers to be sent with all calls }, l = U(this.url, t); try { const r = await k(l, { body: s ? JSON.stringify(s) : null, headers: c, method: "POST" }); if (!r.ok) { let u; return (i = r.headers.get("content-type")) != null && i.includes("application/json") ? u = await r.json() : u = await r.text(), { res: null, error: { message: u, error: r.statusText, status: r.status } }; } let n; return (h = r.headers.get("content-type")) != null && h.includes("application/json") ? n = await r.json() : n = await r.text(), { res: { data: n, status: r.status, statusText: r.statusText }, error: null }; } catch (r) { const n = r; return { res: null, error: { message: n.message, status: n.name === "AbortError" ? 0 : 500, error: n.name === "AbortError" ? "abort-error" : "unknown" } }; } } /** * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically. * * @example * ```ts * nhost.functions.setAccessToken('some-access-token') * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token */ setAccessToken(t) { if (!t) { this.accessToken = null; return; } this.accessToken = t; } /** * Use `nhost.functions.getHeaders` to get the global headers sent with all functions requests. * * @example * ```ts * nhost.functions.getHeaders() * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/get-headers */ getHeaders() { return this.headers; } /** * Use `nhost.functions.setHeaders` to a set global headers to be sent in all subsequent functions requests. * * @example * ```ts * nhost.functions.setHeaders({ * 'x-hasura-role': 'admin' * }) * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-headers */ setHeaders(t) { t && (this.headers = { ...this.headers, ...t }); } /** * Use `nhost.functions.unsetHeaders` to a unset global headers sent with all functions requests. * * @example * ```ts * nhost.functions.unsetHeaders() * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/unset-headers */ unsetHeaders() { const t = this.headers["x-hasura-role"]; this.headers = t ? { "x-hasura-role": t } : {}; } generateAccessTokenHeaders() { return this.adminSecret ? { "x-hasura-admin-secret": this.adminSecret } : this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}; } } function _(e) { const t = "subdomain" in e ? f(e, "graphql") : e.graphqlUrl; if (!t) throw new Error("Please provide `subdomain` or `graphqlUrl`."); return new b({ url: t, ...e }); } function q(e) { const t = "subdomain" in e ? f(e, "storage") : e.storageUrl; if (!t) throw new Error("Please provide `subdomain` or `storageUrl`."); return new w({ url: t, ...e }); } const F = (e) => new E(e); class E { /** * * @example * ```ts * // Create a new Nhost client from subdomain and region. * const nhost = new NhostClient({ subdomain, region }); * ``` * * * ```ts * // Create a new Nhost client from individual service URLs (custom domains, self-hosting, etc). * const nhost = new NhostClient({ * authUrl: "my-auth-service-url", * storageUrl: "my-storage-service-url", * graphqlUrl: "my-graphql-service-url", * functionsUrl: "my-functions-service-url", * }); * ``` * * * ```ts * // Create a new Nhost client for local development. * const nhost = new NhostClient({ subdomain: "local" }); * ``` * * @docs https://docs.nhost.io/reference/javascript */ constructor({ refreshIntervalTime: t, clientStorage: s, clientStorageType: o, autoRefreshToken: c, autoSignIn: l, adminSecret: i, devTools: h, start: r = !0, ...n }) { a(this, "auth"); a(this, "storage"); a(this, "functions"); a(this, "graphql"); a(this, "_adminSecret"); a(this, "devTools"); this.auth = $({ refreshIntervalTime: t, clientStorage: s, clientStorageType: o, autoRefreshToken: c, autoSignIn: l, start: r, ...n }), this.storage = q({ adminSecret: i, ...n }), this.functions = v({ adminSecret: i, ...n }), this.graphql = _({ adminSecret: i, ...n }), this.auth.onAuthStateChanged((u, d) => { if (u === "SIGNED_OUT") { this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0); return; } const g = d == null ? void 0 : d.accessToken; this.storage.setAccessToken(g), this.functions.setAccessToken(g), this.graphql.setAccessToken(g); }), this.auth.onTokenChanged((u) => { const d = u == null ? void 0 : u.accessToken; this.storage.setAccessToken(d), this.functions.setAccessToken(d), this.graphql.setAccessToken(d); }), this._adminSecret = i, this.devTools = h; } get adminSecret() { return this._adminSecret; } set adminSecret(t) { this._adminSecret = t, this.storage.setAdminSecret(t); } /** * Use `nhost.setRole` to set the user role for all subsequent GraphQL, storage, and functions calls. * Underneath, this method sets the `x-hasura-role` header on the graphql, storage, * and functions clients. * * ```ts * nhost.graphql.setHeaders({ 'x-hasura-role': role }) * nhost.storage.setHeaders({ 'x-hasura-role': role }) * nhost.functions.setHeaders({ 'x-hasura-role': role }) * ``` * * Note: Exercise caution when mixing the use of `setRole` along with `setHeaders` when setting the * `x-hasura-role` header, as the last call will override any previous ones. * * @example * ```ts * nhost.setRole('admin') * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/set-role */ setRole(t) { this.graphql.setHeaders({ "x-hasura-role": t }), this.storage.setHeaders({ "x-hasura-role": t }), this.functions.setHeaders({ "x-hasura-role": t }); } /** * Use `nhost.unsetRole` to unset the user role for all subsequent graphql, storage and functions calls. * Underneath, this method removes the `x-hasura-role` header from the graphql, storage and functions clients. * * Note: Exercise caution when mixing the use of `unsetRole` along with `setHeaders` when setting the * `x-hasura-role` header, as the last call will override any previous ones. * * @example * ```ts * nhost.unsetRole() * ``` * * @docs https://docs.nhost.io/reference/javascript/nhost-js/unset-role */ unsetRole() { this.graphql.setHeaders((({ "x-hasura-role": t, ...s }) => s)(this.graphql.getHeaders())), this.storage.setHeaders((({ "x-hasura-role": t, ...s }) => s)(this.storage.getHeaders())), this.functions.setHeaders( (({ "x-hasura-role": t, ...s }) => s)(this.functions.getHeaders()) ); } } export { E as NhostClient, C as NhostFunctionsClient, $ as createAuthClient, v as createFunctionsClient, _ as createGraphqlClient, F as createNhostClient, q as createStorageClient, f as urlFromSubdomain }; //# sourceMappingURL=index.esm.js.map