Coder Social home page Coder Social logo

dandv / jetblack-graphql-client Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rob-blackbourn/jetblack-graphql-client

0.0 1.0 0.0 159 KB

A simple non-caching GraphQL client for query, mutation and subscription

License: Apache License 2.0

JavaScript 100.00%

jetblack-graphql-client's Introduction

jetblack-graphql-client

This is work in progress.

Overview

A simple non-caching GraphQL client for query, mutation and subscription.

I wanted a simple non-caching GraphQL subscription client written in ES6 javascript with no external dependencies.

The protocol for GraphQL WebSocket subscriptions can be found here.

This implementation is deliberately explicit and low on features as I wanted to keep the algorithm clear. Features like observables and caching should be implmented in other libraries. For example see here for a reconnecting subscriber.

Installation

Install from npm.

yarn add @jetblack/graphql-client

Usage

There are two functions:

  • graphQLSubscriber (url, options, callback, protocols = 'graphql-ws')
  • graphQLFetch (url, query, variables = {}, operationName = null, init = fetchOptions)

The graphQLSubscriber implements the WebSocket protocol. The function takes the url for the WebSocket, an options object which is simply passed as JSON to the server, and a callback with the prototype (error, subscribe). A function is returned which can be used to shutdown the subscriber. If both error and subscribe are null the connection has been closed normally.

The subscribe argument is a function with the prototype subscribe(query, variables, operationName, callback). When subscribe is called it returns a function that can be called to unsubscribe. The callback to the subscribe function has the prototype callback(error, data). If both error and data are null then connection hs been closed normally.

The protocols defaults to "graphql-ws". The documentation suggests this can be an array or strings, but the first should be the default.

The graphQLFetch function is a simple fetch implementation for query and mutation operations. There are numerous implementations of this available, and it is provided for convenience. The init parameter is passed through to fetch. It has the default value fetchOptions which is defined as:

const fetchOptions = {
  method: 'post',
  headers: { 'Content-Type': 'application/json' }
}

// The fetchOptions can be extended.
const myFetchOptions = {
    ...fetchOptions,
    mode: 'cors'
}

There follows an example of the graphQLSubscriber.

import { Subscriber } from '@jetblack/graphql-client'

const url = 'ws://localhost/subscriptions'
const options = {}

const query = `
subscription {
    mySubscription {
        someData
    }
}
`
variables = {}
operationName = null

const shutdown = graphQLSubscriber(
    url,
    options,
    (error, subscribe) => {
        if (!(error || subscribe)) {
            // Normal closure.
            return
        }
        if (error) {
            console.error(error)
            throw error
        }
        const unsubscribe = subscribe(
            query,
            variables,
            operationName,
            (error, data) => {
                if (!(error || subscribe)) {
                    // Normal closure
                    return
                }
                if (error) {
                    console.error(error)
                    throw error
                }
                console.log(data)
            })
        
        // Some time later ...
        unsubscribe()
    })

// Some time later ...
shutdown()

The graphQLFetch function is used as follows.

import { Fetcher } from '@jetblack/graphql-client'

const fetcher = new RetryFetcher('http://localhost/graphql')

// An example mutation.
graphQLFetch(
    `
mutate CreditAccount($account: ID!, $amount: Float!) {
    creditAccount(account: $account, amount: $amount) {
        balance
    }
}`,
    {
        account: '1234',
        amount: 19.99
    }
)
.then(respoonse => response.json())
.then(response => {
    console.log(response.data.balance)
})
.catch(error => {
    console.error(error)
})

jetblack-graphql-client's People

Contributors

rob-blackbourn avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.