tinygql
Version:
A tiny GraphQL browser client with zero dependencies
1 lines • 1.88 kB
JavaScript
!function(e,r){"function"==typeof define&&define.amd?define([],r):"object"==typeof module&&module.exports?module.exports=r():e.TinyGQL=r()}(this,function(){function e(e){e=e||{},this.opts={url:e.url||"/graphql",sendModifier:e.sendModifier||null},this.fragments={}}function r(e,n,s){s=s||{};for(var t,o=/\.\.\.\s*([_A-Za-z][_0-9A-Za-z]*)\s/g;null!==(t=o.exec(e));){var i=t[1];"on"!==i&&!s[i]&&n[i]&&(s[i]=n[i],r(n[i],n,s))}return s}function n(e,r,n,s){var t=[];for(var o in s)t.push(s[o]);e=[e].concat(t).join("\n");var i={query:e};return r&&(i.variables=r),n&&(i.operationName=n),i}function s(e,r){var n=new XMLHttpRequest;n.responseType="json",n.open("POST",e),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("Accept","application/json"),n.onload=function(){if(n.status<200||n.status>299)return s(new Error("request status code is "+n.status));if("string"==typeof n.response&&(n.response=JSON.parse(n.response)),!n.response||!n.response.data&&!n.response.errors)return s(new Error("invalid response "+JSON.stringify(n.response)));if(n.response.errors){var e=new Error("the GraphQL response has errors "+JSON.stringify(n.response.errors));e.name="TinyGQLQueryError",e.raw=n.response.errors,r(e,null)}else r(null,n.response.data)},n.onerror=s;var s=function(e){e.name="TinyGQLRequestError",r(e,null)};return n}return e.prototype.storeFragment=function(e){var r=/fragment\s*([_A-Za-z][_0-9A-Za-z]*)\s/,n=r.exec(e);if(!n)throw new Error("TinyGQL.storeFragment() - no fragment name found!");var s=n[1];return this.fragments[s]=e.trim(),s},e.prototype.removeFragment=function(e){delete this.fragments[e]},e.prototype.send=function(e,t){var o=e.query||e.mutation,i=e.variables,a=e.operationName,u=e.sendModifier||this.sendModifier,p=r(o,this.fragments),f=n(o,i,a,p),d=s(this.opts.url,t);if(u){var l=u({xhr:d,body:f});f=l.body,d=l.xhr}d.send(JSON.stringify(f))},e});