@nhost/nhost-js
Advanced tools
Comparing version 2.2.0 to 2.2.1
@@ -16,5 +16,7 @@ import { NhostClientConstructorParams } from '../../utils/types'; | ||
/** | ||
* Use `nhost.functions.call` to call (sending a POST request to) a serverless function. | ||
* 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 | ||
@@ -24,5 +26,34 @@ * 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 | ||
*/ | ||
call<T = unknown, D = any>(url: string, body: D | null, config?: NhostFunctionCallConfig): Promise<NhostFunctionCallResponse<T>>; | ||
call<TData = unknown, TBody = any, TErrorMessage = any>(url: string, body?: TBody | null, config?: NhostFunctionCallConfig): Promise<NhostFunctionCallResponse<TData, TErrorMessage>>; | ||
/** | ||
@@ -29,0 +60,0 @@ * 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. |
@@ -12,5 +12,5 @@ import { ErrorPayload } from '../../utils/types'; | ||
} | ||
export type NhostFunctionCallResponse<T = unknown> = { | ||
export type NhostFunctionCallResponse<TData = unknown, TErrorMessage = any> = { | ||
res: { | ||
data: T; | ||
data: TData; | ||
status: number; | ||
@@ -22,3 +22,3 @@ statusText: string; | ||
res: null; | ||
error: ErrorPayload; | ||
error: ErrorPayload<TErrorMessage>; | ||
}; | ||
@@ -25,0 +25,0 @@ /** Subset of RequestInit parameters that are supported by the functions client */ |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@nhost/hasura-auth-js"),g=require("@nhost/hasura-storage-js"),U=require("isomorphic-unfetch"),C=require("@nhost/graphql-js"),A=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{backendUrl:i,subdomain:r,region:u}=t;if(i)return`${i}/v1/${e}`;if(!r)throw new Error("Either `backendUrl` or `subdomain` must be set.");const c=r.match(A);if(c!=null&&c.groups){const{protocol:s,host:n,port:o}=c.groups,l=v(e);return l||(n==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${s||"http"}://localhost:${o||1337}/v1/${e}`):o?`${s||"https"}://local.${e}.nhost.run:${o}/v1`:`${s||"https"}://local.${e}.nhost.run/v1`)}if(!u)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${r}.${e}.${u}.nhost.run/v1`}function m(){return typeof window<"u"}function $(){return typeof process<"u"&&process.env}function v(t){return m()||!$()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function q(t,e){const r=e.startsWith("/")?e:`/${e}`;return t+r}function b(t){const e="subdomain"in t||"backendUrl"in t?d(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new f.HasuraAuthClient({url:e,...t})}function p(t){const e="subdomain"in t||"backendUrl"in t?d(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new w({url:e,...t})}class w{constructor(e){const{url:i,adminSecret:r}=e;this.url=i,this.accessToken=null,this.adminSecret=r}async call(e,i,r){var s;const u={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...r==null?void 0:r.headers},c=q(this.url,e);try{const n=await U(c,{body:i?JSON.stringify(i):null,headers:u,method:"POST"});if(!n.ok)throw new Error(n.statusText);let o;return(s=n.headers.get("content-type"))!=null&&s.includes("application/json")?o=await n.json():o=await n.text(),{res:{data:o,status:n.status,statusText:n.statusText},error:null}}catch(n){const o=n;return{res:null,error:{message:o.message,status:o.name==="AbortError"?0:500,error:o.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function T(t){const e="subdomain"in t||"backendUrl"in t?d(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new C.NhostGraphqlClient({url:e,...t})}function k(t){const e="subdomain"in t||"backendUrl"in t?d(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new g.HasuraStorageClient({url:e,...t})}const y=t=>new S(t);class S{constructor({refreshIntervalTime:e,clientStorage:i,clientStorageType:r,autoRefreshToken:u,autoSignIn:c,adminSecret:s,devTools:n,start:o=!0,...l}){this.auth=b({refreshIntervalTime:e,clientStorage:i,clientStorageType:r,autoRefreshToken:u,autoSignIn:c,start:o,...l}),this.storage=k({adminSecret:s,...l}),this.functions=p({adminSecret:s,...l}),this.graphql=T({adminSecret:s,...l}),this.auth.onAuthStateChanged((a,h)=>{a==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(a=>{const h=a==null?void 0:a.accessToken;this.storage.setAccessToken(h),this.functions.setAccessToken(h),this.graphql.setAccessToken(h)}),this._adminSecret=s,this.devTools=n}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}exports.NhostClient=S;exports.NhostFunctionsClient=w;exports.createAuthClient=b;exports.createFunctionsClient=p;exports.createGraphqlClient=T;exports.createNhostClient=y;exports.createStorageClient=k;for(const t in f)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>f[t]});for(const t in g)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>g[t]}); | ||
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@nhost/hasura-auth-js"),g=require("@nhost/hasura-storage-js"),U=require("isomorphic-unfetch"),C=require("@nhost/graphql-js"),A=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{backendUrl:i,subdomain:s,region:l}=t;if(i)return`${i}/v1/${e}`;if(!s)throw new Error("Either `backendUrl` or `subdomain` must be set.");const c=s.match(A);if(c!=null&&c.groups){const{protocol:o,host:u,port:r}=c.groups,n=v(e);return n||(u==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${o||"http"}://localhost:${r||1337}/v1/${e}`):r?`${o||"https"}://local.${e}.nhost.run:${r}/v1`:`${o||"https"}://local.${e}.nhost.run/v1`)}if(!l)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${s}.${e}.${l}.nhost.run/v1`}function m(){return typeof window<"u"}function $(){return typeof process<"u"&&process.env}function v(t){return m()||!$()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function y(t,e){const s=e.startsWith("/")?e:`/${e}`;return t+s}function p(t){const e="subdomain"in t||"backendUrl"in t?d(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new f.HasuraAuthClient({url:e,...t})}function b(t){const e="subdomain"in t||"backendUrl"in t?d(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new w({url:e,...t})}class w{constructor(e){const{url:i,adminSecret:s}=e;this.url=i,this.accessToken=null,this.adminSecret=s}async call(e,i,s){var o,u;const l={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s==null?void 0:s.headers},c=y(this.url,e);try{const r=await U(c,{body:i?JSON.stringify(i):null,headers:l,method:"POST"});if(!r.ok){let a;return(o=r.headers.get("content-type"))!=null&&o.includes("application/json")?a=await r.json():a=await r.text(),{res:null,error:{message:a,error:r.statusText,status:r.status}}}let n;return(u=r.headers.get("content-type"))!=null&&u.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"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function T(t){const e="subdomain"in t||"backendUrl"in t?d(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new C.NhostGraphqlClient({url:e,...t})}function k(t){const e="subdomain"in t||"backendUrl"in t?d(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new g.HasuraStorageClient({url:e,...t})}const q=t=>new S(t);class S{constructor({refreshIntervalTime:e,clientStorage:i,clientStorageType:s,autoRefreshToken:l,autoSignIn:c,adminSecret:o,devTools:u,start:r=!0,...n}){this.auth=p({refreshIntervalTime:e,clientStorage:i,clientStorageType:s,autoRefreshToken:l,autoSignIn:c,start:r,...n}),this.storage=k({adminSecret:o,...n}),this.functions=b({adminSecret:o,...n}),this.graphql=T({adminSecret:o,...n}),this.auth.onAuthStateChanged((a,h)=>{a==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(a=>{const h=a==null?void 0:a.accessToken;this.storage.setAccessToken(h),this.functions.setAccessToken(h),this.graphql.setAccessToken(h)}),this._adminSecret=o,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}exports.NhostClient=S;exports.NhostFunctionsClient=w;exports.createAuthClient=p;exports.createFunctionsClient=b;exports.createGraphqlClient=T;exports.createNhostClient=q;exports.createStorageClient=k;for(const t in f)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>f[t]});for(const t in g)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>g[t]}); | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -5,21 +5,21 @@ import { HasuraAuthClient as f } from "@nhost/hasura-auth-js"; | ||
export * from "@nhost/hasura-storage-js"; | ||
import w from "isomorphic-unfetch"; | ||
import { NhostGraphqlClient as p } from "@nhost/graphql-js"; | ||
import p from "isomorphic-unfetch"; | ||
import { NhostGraphqlClient as w } from "@nhost/graphql-js"; | ||
const b = /^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/; | ||
function d(e, t) { | ||
const { backendUrl: i, subdomain: r, region: l } = e; | ||
const { backendUrl: i, subdomain: o, region: a } = e; | ||
if (i) | ||
return `${i}/v1/${t}`; | ||
if (!r) | ||
if (!o) | ||
throw new Error("Either `backendUrl` or `subdomain` must be set."); | ||
const c = r.match(b); | ||
if (c != null && c.groups) { | ||
const { protocol: s, host: n, port: o } = c.groups, u = m(t); | ||
return u || (n === "localhost" ? (console.warn( | ||
const u = o.match(b); | ||
if (u != null && u.groups) { | ||
const { protocol: s, host: c, port: r } = u.groups, n = k(t); | ||
return n || (c === "localhost" ? (console.warn( | ||
'The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.' | ||
), `${s || "http"}://localhost:${o || 1337}/v1/${t}`) : o ? `${s || "https"}://local.${t}.nhost.run:${o}/v1` : `${s || "https"}://local.${t}.nhost.run/v1`); | ||
), `${s || "http"}://localhost:${r || 1337}/v1/${t}`) : r ? `${s || "https"}://local.${t}.nhost.run:${r}/v1` : `${s || "https"}://local.${t}.nhost.run/v1`); | ||
} | ||
if (!l) | ||
if (!a) | ||
throw new Error('`region` must be set when using a `subdomain` other than "local".'); | ||
return `https://${r}.${t}.${l}.nhost.run/v1`; | ||
return `https://${o}.${t}.${a}.nhost.run/v1`; | ||
} | ||
@@ -29,11 +29,11 @@ function T() { | ||
} | ||
function k() { | ||
function m() { | ||
return typeof process < "u" && process.env; | ||
} | ||
function m(e) { | ||
return T() || !k() ? null : process.env[`NHOST_${e.toUpperCase()}_URL`]; | ||
function k(e) { | ||
return T() || !m() ? null : process.env[`NHOST_${e.toUpperCase()}_URL`]; | ||
} | ||
function U(e, t) { | ||
const r = t.startsWith("/") ? t : `/${t}`; | ||
return e + r; | ||
const o = t.startsWith("/") ? t : `/${t}`; | ||
return e + o; | ||
} | ||
@@ -54,33 +54,42 @@ function S(e) { | ||
constructor(t) { | ||
const { url: i, adminSecret: r } = t; | ||
this.url = i, this.accessToken = null, this.adminSecret = r; | ||
const { url: i, adminSecret: o } = t; | ||
this.url = i, this.accessToken = null, this.adminSecret = o; | ||
} | ||
async call(t, i, r) { | ||
var s; | ||
const l = { | ||
async call(t, i, o) { | ||
var s, c; | ||
const a = { | ||
"Content-Type": "application/json", | ||
...this.generateAccessTokenHeaders(), | ||
...r == null ? void 0 : r.headers | ||
}, c = U(this.url, t); | ||
...o == null ? void 0 : o.headers | ||
}, u = U(this.url, t); | ||
try { | ||
const n = await w(c, { | ||
const r = await p(u, { | ||
body: i ? JSON.stringify(i) : null, | ||
headers: l, | ||
headers: a, | ||
method: "POST" | ||
}); | ||
if (!n.ok) | ||
throw new Error(n.statusText); | ||
let o; | ||
return (s = n.headers.get("content-type")) != null && s.includes("application/json") ? o = await n.json() : o = await n.text(), { | ||
res: { data: o, status: n.status, statusText: n.statusText }, | ||
if (!r.ok) { | ||
let l; | ||
return (s = r.headers.get("content-type")) != null && s.includes("application/json") ? l = await r.json() : l = await r.text(), { | ||
res: null, | ||
error: { | ||
message: l, | ||
error: r.statusText, | ||
status: r.status | ||
} | ||
}; | ||
} | ||
let n; | ||
return (c = r.headers.get("content-type")) != null && c.includes("application/json") ? n = await r.json() : n = await r.text(), { | ||
res: { data: n, status: r.status, statusText: r.statusText }, | ||
error: null | ||
}; | ||
} catch (n) { | ||
const o = n; | ||
} catch (r) { | ||
const n = r; | ||
return { | ||
res: null, | ||
error: { | ||
message: o.message, | ||
status: o.name === "AbortError" ? 0 : 500, | ||
error: o.name === "AbortError" ? "abort-error" : "unknown" | ||
message: n.message, | ||
status: n.name === "AbortError" ? 0 : 500, | ||
error: n.name === "AbortError" ? "abort-error" : "unknown" | ||
} | ||
@@ -109,3 +118,3 @@ }; | ||
throw new Error("Please provide `subdomain` or `graphqlUrl`."); | ||
return new p({ url: t, ...e }); | ||
return new w({ url: t, ...e }); | ||
} | ||
@@ -123,9 +132,9 @@ function C(e) { | ||
clientStorage: i, | ||
clientStorageType: r, | ||
autoRefreshToken: l, | ||
autoSignIn: c, | ||
clientStorageType: o, | ||
autoRefreshToken: a, | ||
autoSignIn: u, | ||
adminSecret: s, | ||
devTools: n, | ||
start: o = !0, | ||
...u | ||
devTools: c, | ||
start: r = !0, | ||
...n | ||
}) { | ||
@@ -135,13 +144,13 @@ this.auth = S({ | ||
clientStorage: i, | ||
clientStorageType: r, | ||
autoRefreshToken: l, | ||
autoSignIn: c, | ||
start: o, | ||
...u | ||
}), this.storage = C({ adminSecret: s, ...u }), this.functions = A({ adminSecret: s, ...u }), this.graphql = v({ adminSecret: s, ...u }), this.auth.onAuthStateChanged((a, h) => { | ||
a === "SIGNED_OUT" && (this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0)); | ||
}), this.auth.onTokenChanged((a) => { | ||
const h = a == null ? void 0 : a.accessToken; | ||
clientStorageType: o, | ||
autoRefreshToken: a, | ||
autoSignIn: u, | ||
start: r, | ||
...n | ||
}), this.storage = C({ adminSecret: s, ...n }), this.functions = A({ adminSecret: s, ...n }), this.graphql = v({ adminSecret: s, ...n }), this.auth.onAuthStateChanged((l, h) => { | ||
l === "SIGNED_OUT" && (this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0)); | ||
}), this.auth.onTokenChanged((l) => { | ||
const h = l == null ? void 0 : l.accessToken; | ||
this.storage.setAccessToken(h), this.functions.setAccessToken(h), this.graphql.setAccessToken(h); | ||
}), this._adminSecret = s, this.devTools = n; | ||
}), this._adminSecret = s, this.devTools = c; | ||
} | ||
@@ -148,0 +157,0 @@ get adminSecret() { |
import { NhostAuthConstructorParams } from '@nhost/hasura-auth-js'; | ||
export interface ErrorPayload { | ||
export interface ErrorPayload<TMessage = any> { | ||
error: string; | ||
status: number; | ||
message: string; | ||
message: TMessage; | ||
} | ||
@@ -7,0 +7,0 @@ export interface ActionErrorState { |
{ | ||
"name": "@nhost/nhost-js", | ||
"version": "2.2.0", | ||
"version": "2.2.1", | ||
"description": "Nhost JavaScript SDK", | ||
@@ -53,3 +53,3 @@ "license": "MIT", | ||
"graphql": "16.6.0", | ||
"@nhost/docgen": "0.1.8" | ||
"@nhost/docgen": "0.1.9" | ||
}, | ||
@@ -56,0 +56,0 @@ "peerDependencies": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
639018
918