UNPKG

@nhost/graphql-js

Version:

Nhost GraphQL client

3 lines (2 loc) 2.64 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("isomorphic-unfetch"),c=require("graphql"),m=require("jwt-decode");function g(r,e,s){return r.document?r:{document:r,variables:e,config:s}}function l(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 k(r){if(typeof r=="string"){let s;try{const n=c.parse(r);s=l(n)}catch{}return{query:r,operationName:s}}const e=l(r);return{query:c.print(r),operationName:e}}class y{constructor(e){this.headers={},this.isAccessTokenValidOrNull=()=>{if(!this.accessToken)return!0;try{const t=m.jwtDecode(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:h,...d}=t||{},{query:p,operationName:f}=k(i.document);typeof process!="undefined"&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const a=await T(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:p,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...h},...d});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"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}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}`}:{}}}exports.NhostGraphqlClient=y; //# sourceMappingURL=index.cjs.js.map