Accessing your GraphQL endpoint

Using a js client to access your GraphQL

Intro

Let’s create a simple javascript object/library to access our graphql-backend.

This will be considered version 1.0 and we will probably enhance it later as the need arises.

Code

var gql = {
  version: '1.0',
  _endpoint: 'https://rj07ty7re4.execute-api.us-east-1.amazonaws.com/dev/gql', 
  pendingQueries: [], 
  pendingFragments: [],
  send: async function (querystring) { 
    querystring = querystring || '';
    let ep = this._endpoint;
    let query = this.pop();
    let response = await fetch(ep + querystring, { 
        method: 'POST',
        mode: 'cors',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ query: query /* variables: */ })
      });
    return response.json();
  },
  init: function (endpoint) {
    this._endpoint = endpoint;
  },
  pop: function () {
    let q = '';
    this.pendingQueries.forEach((qry) => {
      q += `${qry.name}: ${qry.q} `;
    });
    q = `{ ${q} }`;
    this.pendingFragments.forEach((frag) => {
      q += ` ${frag}`;
    });
    this.pendingQueries = [];
    this.pendingFragments = [];
    return q;
  },
  query: function (name, fields, args, dataName) { 
    dataName = dataName || name;
    let q = `${name} { ${fields} }`;
    if (args) {
      q = `${name}(${args}) { ${fields} }`;
    }
    let qry = {
      name: dataName,
      q: q
    };
    this.pendingQueries.push(qry);
  }
};

This is our base object

Directions

(1) _endpoint

This is where our backend lives. You should change this url to yours.

init(endpoint)

This can be called to set an endpoint right after we import our lib

// in our html
<script src="/lib/gql.js"></script>
<script>
  gql.init(endpoint);
</script>

(2) pendingQueries[]

Because GraphQL can respond to multiple queries at the same time (same request), this internal array will keep track of the queries we prepare and will queue them until we explicitly send them.

(3) send()

This method will send our queued queries. It uses the pop() method to prepare the queries we’ve queued, and then reset out internal arrays/state.

(4) query()

Prepare a query, give it a name in case we want to request it multiple times with different arguments, specify the field list…

Examples

gql.query(
  'allPokemon', 
  'items { id name type1 type2 stats { attack defense stamina } }',
  'page: 2, itemsPerPage: 4'
);
gql.query(
  'pokemon',
  'name type1 type2 evolvesTo { name }',
  'id: "bulbasaur"',
  'bulbasaur'
);
gql.query(
  'pokemon',
  'name type1 type2 evolvesTo { name }',
  'id: "squirtle"',
  'squirtle'
);
gql.send()
.then((result) => {
  console.log(result);
});

The above will produce the following graphql query:

{
  allPokemon: allPokemon(page: 2, itemsPerPage: 4) { 
    items { id name type1 type2 stats { attack defense stamina } } 
  }
  bulbasaur: pokemon(id: "bulbasaur") {
    name type1 type2 evolvesTo { name }
  }
  squirtle: pokemon(id: "squirtle") {
    name type1 type2 evolvesTo { name }
  }
}

and the response from the backend lloks something like:

{
  "data": {
    "allPokemon": {
      "items": [
        {
          "id": "CHARMELEON", "name": "CHARMELEON",
          "type1": "FIRE", "type2": null,
          "stats": {
            "attack": 158, "defense": 126, "stamina": 151
          }
        },
        {
          "id": "CHARIZARD", "name": "CHARIZARD",
          "type1": "FIRE", "type2": "FLYING",
          "stats": {
            "attack": 223, "defense": 173, "stamina": 186
          }
        },
        {
          "id": "SQUIRTLE", "name": "SQUIRTLE",
          "type1": "WATER", "type2": null,
          "stats": {
            "attack": 94, "defense": 121, "stamina": 127
          }
        },
        {
          "id": "WARTORTLE", "name": "WARTORTLE",
          "type1": "WATER", "type2": null,
          "stats": {
            "attack": 126, "defense": 155, "stamina": 153
          }
        }
      ]
    },
    "bulbasaur": {
      "name": "BULBASAUR",
      "type1": "GRASS", "type2": "POISON",
      "evolvesTo": [ { "name": "IVYSAUR" } ]
    },
    "squirtle": {
      "name": "SQUIRTLE",
      "type1": "WATER", "type2": null,
      "evolvesTo": [ { "name": "WARTORTLE" } ]
    }
  }
}

Conclusion

This client lib gives us basic access to our graphql backend.



Back to Post List
ok!