1
\$\begingroup\$

The goal of this is to create an easy to use front-end interface to work with graphql APIs. Can anyone tell me if there are any inefficiencies or areas of improvement on my implementation? It would be much appreciated!

// @flow

import 'whatwg-fetch'

let uri: string = ''
let headers: Object = {}

function compile(strs: Array<string>, expressions: Array<any>): string {
  let query: string = strs[0]
  for (let i: number = 0; i < expressions.length; i++)
    query += `${expressions[i]}${strs[i + 1]}`
  return query
}

function post(query: string): Promise<Object> {
  return fetch(uri, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query
    })
  }).then(res => res.json())
    .then(json => json.data)
    .catch(err => err)
}

const Ez: Object = {

  config(options: Object): void {
    uri = options.uri || options.url || ''
    headers = options.headers || { 'Content-type': 'application/json' }
  },

  ql(strs: Array<string>, ...exp: Array<any>): Promise<Object> {
    const query: string = compile(strs, exp)

    return post(query)
  },

  pql(query: string): Promise<Object> {
    return post(query)
  }

}

export default Ez

An example call would look something like this:

Ez.ql`
  {
    lot(number: 5) {
      permits
      totalSpaces
    }
  }
`
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.