@nhost/graphql-js
Version:
Nhost GraphQL client
221 lines (220 loc) • 5.94 kB
JavaScript
import f from "isomorphic-unfetch";
import { parse as m, print as T } from "graphql";
import { jwtDecode as k } from "jwt-decode";
function g(r, e, s) {
return r.document ? r : {
document: r,
variables: e,
config: s
};
}
function c(r) {
var n;
let e;
const s = r.definitions.filter(
(t) => t.kind === "OperationDefinition"
);
return s.length === 1 && (e = (n = s[0].name) == null ? void 0 : n.value), e;
}
function y(r) {
if (typeof r == "string") {
let s;
try {
const n = m(r);
s = c(n);
} catch {
}
return { query: r, operationName: s };
}
const e = c(r);
return { query: T(r), operationName: e };
}
class x {
constructor(e) {
this.headers = {}, this.isAccessTokenValidOrNull = () => {
if (!this.accessToken)
return !0;
try {
const t = k(this.accessToken);
return t.exp != null && t.exp * 1e3 > Date.now();
} catch (t) {
return console.error("Error decoding token:", t), !1;
}
}, this.awaitForValidAccessTokenOrNull = async () => {
if (this.isAccessTokenValidOrNull())
return !0;
const t = () => this.isAccessTokenValidOrNull() ? Promise.resolve(!0) : new Promise((i) => {
setTimeout(() => t().then(i), 100);
});
return t();
};
const { url: s, adminSecret: n } = e;
this._url = s, this.accessToken = null, this.adminSecret = n;
}
async request(e, ...s) {
const [n, t] = s, i = g(e, n, t), { headers: l, ...h } = t || {}, { query: d, operationName: p } = y(i.document);
typeof process != "undefined" && !process.env.TEST_MODE && await this.awaitForValidAccessTokenOrNull();
try {
const a = await f(this.httpUrl, {
method: "POST",
body: JSON.stringify({
operationName: p,
query: d,
variables: n
}),
headers: {
"Content-Type": "application/json",
...this.generateAccessTokenHeaders(),
...this.headers,
// graphql client headers to be sent with all `request` calls
...l
// extra headers to be sent with a specific call
},
...h
});
if (!a.ok)
return {
data: null,
error: {
error: a.statusText,
message: a.statusText,
status: a.status
}
};
const { data: o, errors: u } = await a.json();
return u ? {
data: null,
error: u
} : typeof o != "object" || Array.isArray(o) || o === null ? {
data: null,
error: {
error: "invalid-response",
message: "incorrect response data from GraphQL server",
status: 0
}
} : { data: o, error: null };
} catch (a) {
const o = a;
return {
data: null,
error: {
message: o.message,
status: o.name === "AbortError" ? 0 : 500,
error: o.name === "AbortError" ? "abort-error" : "unknown"
}
};
}
}
/**
* Use `nhost.graphql.httpUrl` to get the GraphQL HTTP URL.
* @example
* ```ts
* const url = nhost.graphql.httpUrl;
* ```
*
* @docs https://docs.nhost.io/reference/javascript/graphql/get-http-url
*/
get httpUrl() {
return this._url;
}
/**
* Use `nhost.graphql.wsUrl` to get the GraphQL WebSocket URL.
* @example
* ```ts
* const url = nhost.graphql.wsUrl;
* ```
*
* @docs https://docs.nhost.io/reference/javascript/graphql/get-ws-url
*/
get wsUrl() {
return this._url.replace(/^(http)(s?):\/\//, "ws$2://");
}
/**
* Use `nhost.graphql.url` to get the GraphQL URL.
* @deprecated Use `nhost.graphql.httpUrl` and `nhost.graphql.wsUrl` instead.
*/
get url() {
return this._url;
}
/**
* Use `nhost.graphql.getUrl()` to get the GraphQL URL.
* @deprecated Use `nhost.graphql.httpUrl` and `nhost.graphql.wsUrl` instead.
*/
getUrl() {
return this._url;
}
/**
* Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.
*
* @example
* ```ts
* nhost.graphql.setAccessToken('some-access-token')
* ```
*
* @docs https://docs.nhost.io/reference/javascript/graphql/set-access-token
*/
setAccessToken(e) {
if (!e) {
this.accessToken = null;
return;
}
this.accessToken = e;
}
/**
* Use `nhost.graphql.getHeaders` to get the global headers sent with all graphql requests
*
* @example
* ```ts
* nhost.graphql.getHeaders()
* ```
*
* @docs https://docs.nhost.io/reference/javascript/graphql/get-headers
*/
getHeaders() {
return this.headers;
}
/**
* Use `nhost.graphql.setHeaders` to set global headers to be sent in all subsequent graphql requests
*
* @example
* ```ts
* nhost.graphql.setHeaders({
* 'x-hasura-role': 'admin'
* })
* ```
*
* @docs https://docs.nhost.io/reference/javascript/graphql/set-headers
*/
setHeaders(e) {
e && (this.headers = {
...this.headers,
...e
});
}
/**
* Use `nhost.graphql.unsetHeaders` to remove global headers sent with all requests, except for the role header to preserve
* the role set by 'setRole' method.
*
* @example
* ```ts
* nhost.graphql.unsetHeaders()
* ```
*
* @docs https://docs.nhost.io/reference/javascript/graphql/unset-headers
*/
unsetHeaders() {
const e = this.headers["x-hasura-role"];
this.headers = e ? { "x-hasura-role": e } : {};
}
generateAccessTokenHeaders() {
return this.adminSecret ? {
"x-hasura-admin-secret": this.adminSecret
} : this.accessToken ? {
Authorization: `Bearer ${this.accessToken}`
} : {};
}
}
export {
x as NhostGraphqlClient
};
//# sourceMappingURL=index.esm.js.map