• Stars
    star
    1,532
  • Rank 29,507 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple JavaScript Client for GraphQL

lokka

Simple GraphQL client for JavaScript.

Works on all the JavaScript environments including Browser, NodeJS and React Native.

TOC

Installation

Install lokka and a transport layer:

npm i --save lokka lokka-transport-http

Here we'll be using Lokka's HTTP transport layer which is compatible with express-graphql.

Usage

We can initialize a Lokka client like this:

const Lokka = require('lokka').Lokka;
const Transport = require('lokka-transport-http').Transport;

const client = new Lokka({
  transport: new Transport('http://graphql-swapi.parseapp.com/')
});

Here we connect lokka to Facebook's SWAPI GraphQL Demo.

Core API

Basic Querying

Then you can invoke a simple query like this: (This query will get titles of all the Star Wars films)

client.query(`
    {
      allFilms {
        films {
          title
        }
      }
    }
`).then(result => {
    console.log(result.allFilms);
});

Using Fragments

You can also create fragments and use inside queries.

Let's define a fragment for the Film type.

const filmInfo = client.createFragment(`
  fragment on Film {
    title,
    director,
    releaseDate
  }
`);

NOTE: Here's you don't need to give a name to the fragment

Let's query all the films using the above fragment:

client.query(`
  {
    allFilms {
      films {
        ...${filmInfo}
      }
    }
  }
`).then(result => {
  console.log(result.allFilms.films);
});

We can also use fragments inside fragments as well. Lokka will resolve fragments in nested fashion.

Mutations

GraphQL Swapi API, does not have mutations. If we had mutations we could invoke them like this:

client.mutate(`{
    newFilm: createMovie(
        title: "Star Wars: The Force Awakens",
        director: "J.J. Abrams",
        producers: [
            "J.J. Abrams", "Bryan Burk", "Kathleen Kennedy"
        ],
        releaseDate: "December 14, 2015"
    ) {
        ...${filmInfo}
    }
}`).then(response => {
    console.log(response.newFilm);
});

To send mutations with variable, invoke them like this:

const mutationQuery = `($input: SomeVarType!){
    newData: createData($input) {
        ...${someInfo}
    }
}`;

const vars = {
  input: 'some data here',
};

client.mutate(mutationQuery, vars).then(resp => {
    console.log(resp.newFilm);
});

Normally, when we are sending a GraphQL mutation we write it like below:

mutation someNameForRequest ($vars: SomeVarType) {
  newFilm: createMovie(...) {
    ...
  }
}

But with lokka, you don't need to write mutation someNameForRequest part. Lokka will add it for you.

Query Variables

We can use query variables when querying the schema.

const query = `
  query sumNow($a: Int, $b: Int) {
    sum(a: $a, b: $b)
  }
`;

const vars = {a: 10, b: 30};
client.query(query, vars).then(result => {
  console.log(result.sum);
});

Cache API

Lokka has a built in cache. But it won't be used when you are invoking the core API. For that, you need to use following APIs:

Lokka.watchQuery()

This API allows to watch a query. First it will fetch the query and cache it. When the cache updated, it'll notify the change. Here's how to use it.

// create a query with query variables (query variables are not mandatory)
const query = `
  query _($message: String!) {
    echo(message: $message)
  }
`;
// object pass as the query variables
const vars = {message: 'Hello'};

// create a lokka client with a transport
const client = new Lokka({...});

// watch the query
const watchHandler = (err, payload) => {
  if (err) {
    console.error(err.message);
    return;
  }

  console.log(payload.echo);
};
const stop = client.watchQuery(query, vars, watchHandler);

// stop watching after a minute
setTimeout(stop, 1000 * 60);

Lokka.refetchQuery()

Refetch a given query and update the cache:

client.refetchQuery(query, {message: 'Hello Again'});

This will notify all the watch handlers registered with BlogSchema.watchQuery.

Lokka.cache.getItemPayload()

Get the item inside the cache for a query.

const payload = client.cache.getItemPayload(query, vars);

Lokka.cache.setItemPayload()

Set the item inside the cache. New value will be send to all registered watch handlers.

client.cache.setItemPayload(query, vars, payload);

Payload must to identical to what's receive from the GraphQL.

Lokka.cache.removeItem()

With this we can remove the query and vars combo from the cache. But this won't notify watch handers.

client.cache.removeItem(query, vars);

Lokka.cache.fireError()

Fire an error for all the registered watchHandlers.

client.cache.fireError(query, vars, new Error('some error'));

Available Transports

Demo Apps

Have a look at some sample apps:

Future Development

In this version of lokka, it's just a basic API where you can query against a GraphQL Schema. This API is stable.

We'll have more features in the future versions of lokka.

  • 1.x.x - Query/Mutate against a GraphQL schema.
    • support for query variables.
    • query watching support.
    • [current] basic client side cache.
  • 2.x.x - Client side query validations.
  • 3.x.x - Client side smart cache.
  • 4.x.x - Subscriptions Support.

More Repositories

1

flow-router

Carefully Designed Client Side Router for Meteor
JavaScript
1,089
star
2

mantra

Mantra - An Application Architecture for Meteor
Shell
980
star
3

fast-render

Render you app even before the DDP connection is live. - magic?
JavaScript
559
star
4

subs-manager

Subscriptions Manager for Meteor
JavaScript
358
star
5

graphql-errors

Better error handling for GraphQL
JavaScript
253
star
6

blaze-layout

Layout Manager for Blaze (works well with Meteor FlowRouter)
JavaScript
198
star
7

npm-base

A base package for creating NPM packages with ES2015
JavaScript
161
star
8

meteor-debug

Full Stack Debugging Solution for Meteor
JavaScript
152
star
9

meteor-react-layout

Simple React Layout Manager for Meteor with SSR Support
JavaScript
138
star
10

meteor-dochead

Isomorphic way to manipulate document.head for Meteor apps
JavaScript
134
star
11

react-mounter

A simple way to mount React components
JavaScript
130
star
12

meteor-graphql

GraphQL Support for Meteor with Lokka
JavaScript
90
star
13

graphql-blog-schema

GraphQL Schema for a Blog App
CSS
84
star
14

graphqlify

Build GraphQL queries with JavaScript
JavaScript
56
star
15

react-simple-di

Simple Dependancy Injection Solution for React
JavaScript
56
star
16

react-stubber

Simple but useful stubbing solution React
JavaScript
50
star
17

blaze-plus

Adds Props and State Management functionality to Meteor's Blaze Template Engine.
JavaScript
50
star
18

meteor-login-state

Share Login State Between the Domain
JavaScript
45
star
19

meteor-reaktor

Easy to use React Frontend for FlowRouter
JavaScript
42
star
20

lokka-transport-http

HTTP Transport Layer for Lokka
JavaScript
41
star
21

lokka-transport-jwt-auth

Lokka GraphQL Transport with JWT Support
JavaScript
22
star
22

graphql-utils-js

A set of utilities for apps building with graphql-js
JavaScript
20
star
23

mongo-sharded-cluster

Shard MongoDB in the app layer
JavaScript
13
star
24

meteor-stripe-konnect

Stripe for Meteor Apps
JavaScript
12
star
25

mantra-tutor-lessons

11
star
26

kadiyadb

KadiraDB is a low level database for storing time series data
Go
10
star
27

node-eventloop-monitor

Simple way to monitor eventloop blockness in Node.js
JavaScript
9
star
28

nofat

Set of tools to kick start server side ES2016 development
JavaScript
6
star
29

node-base

Base app for all the server side node apps at Kadira
JavaScript
6
star
30

kadira-core

JavaScript
5
star
31

regex-query-filter

JavaScript
3
star
32

storybook-addon-hello

A simple hello-world example addon for storybook
JavaScript
3
star
33

lokka-transport-http-auth

HTTP Transport for Lokka with Basic Auth
JavaScript
2
star
34

meteor-string-highlighter

String Highlighter for Meteor Apps
JavaScript
2
star
35

url-mailer

JavaScript
2
star
36

fastcall

A fast bi-directional communication layer over tcp
Go
2
star
37

storybook-ping-receiver

Listen to anonymous usage pings sent from storybooks
JavaScript
2
star
38

kadira-debug-toy

MeteorToys integration for kadira:debug Package
JavaScript
2
star
39

go-tools

Go tools is a collection of re-usable go packages used by multiple KadiraHQ projects
Go
2
star
40

kadira.io

Kadira Blog
JavaScript
2
star
41

kadiradb-node

NodejS client for KadiraDB metrics database.
JavaScript
1
star
42

mongo-mask

Replaces data with masked values in mongo queries
JavaScript
1
star
43

kadiradb

A real time metrics database which uses KadiraDB under the hood
Go
1
star