Home

Martin Ting edited this page Dec 20, 2016 · 11 revisions
Clone this wiki locally

What is SubQL?

GraphQL is a useful tool to reduce complications in your web API. Much like RESTful APIs, GraphQL APIs works with HTTP as an interface to capture or modify data by providing an application layer data querying system. However, with these API design patterns, there is no easy way to support real time data. SubQL simplifies this process by providing an easy to use library to wrap around your existing GraphQL APIs and enables streaming data from your API using Socket.IO Websockets. Client side applications can subscribe to GraphQL queries and will receive updates to data changes in real time.

SubQL subscription diagram

How to use SubQL?

Server Side Usage

SubQL can be integrated into your existing graphQL server in four steps.

1) Pass the schema as a string into parseSchema

    parseSchema('
      input MessageInput {
        content: String
        author: String
      }
      type Message {
        id: ID!
        content: String
        author: String
      }
      type Query {
        getMessage(id: ID!): Message
      }
      type Mutation {
        createMessage(input: MessageInput): Message
        updateMessage(id: ID!, input: MessageInput): Message
      }
    ');

2) Register all Object types with registerType

    class Message {
      constructor(id, {content, author}) {
        this.id = id;
        this.content = content;
        this.author = author;
      }
    }
    registerType(Message, 'id', 'author');

3) Register all resolver functions with registerResolver

    function getMessage({id}) {
      if (!fakeDatabase[id]) {
        throw new Error('no message exists with id ' + id);
      }
      return new Message(id, fakeDatabase[id]);
    }
    function createMessage({input}) {
      var id = require('crypto').randomBytes(10).toString('hex');
      fakeDatabase[id] = input;
      return new Message(id, input);
    }
    function updateMessage({id, input}) {
      if (!fakeDatabase[id]) {
        throw new Error('no message exists with id ' + id);
      }
      // This replaces all old data, but some apps might want partial update.
      fakeDatabase[id] = input;
      return new Message(id, input);
    }
    registerResolver(getMessage, createMessage, updateMessage);

4) Call getRoot to retrieve the root object

    var root = getRoot();

Client Side Usage

SubQL provides a very simple client side library to make and subscribe to your graphQL API.

    subscribe('www.subql.io/graphql', 
      '{ getMessage(id: 0) { content} }', 
      null, 
      function (data) {
        console.log(data);
      }
    );