Are you happy with your logging solution? Would you help us out by taking a 30-second survey? Click here

lokka

Simple JavaScript Client for GraphQL

Subscribe to updates I use lokka


Statistics on lokka

Number of watchers on Github 1265
Number of open issues 34
Average time to close an issue about 17 hours
Main language JavaScript
Average time to merge a PR about 22 hours
Open pull requests 7+
Closed pull requests 0+
Last commit almost 3 years ago
Repo Created over 3 years ago
Repo Last Updated over 1 year ago
Size 49 KB
Organization / Authorkadirahq
Contributors1
Page Updated
Do you use lokka? Leave a review!
View open issues (34)
View lokka activity
View on github
Fresh, new opensource launches 🚀🚀🚀
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating lokka for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

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.
lokka open issues Ask a question     (View All Issues)
  • almost 3 years Adding a query builder to Lokka
  • almost 3 years webpack error
  • almost 3 years get value of extensions entry
  • about 3 years How to use cache simply !?
  • about 3 years Lokka seems to be incompatible with React Native
  • about 3 years Using lokka in a traditional SPA
  • over 3 years Upload binary files
  • over 3 years How can I mutate the array?
  • over 3 years Lokka with components (like Relay)
  • over 3 years Make cache management a separate npm module?
  • over 3 years Batch queries and mutations
  • over 3 years Publish to CDN
  • over 3 years check diff payloads
  • over 3 years Keep error inside the cache
  • over 3 years Client side query validations
  • over 2 years babel-runtime dependency adds 400kb+ to compiled build
  • over 2 years retries?
  • over 2 years "Critical Dependencies" Warning
lokka open pull requests (View All Pulls)
  • Publish `lib` to the npm package.
  • Add query string transport link
  • for better coding style in the future
  • Fix typo in README.md
  • Try to add support for recursion in fragments. Parsing fragment name from fragment code.
  • Allow for querying with operationName
  • Allow Searches with ellipses
lokka list of languages used
Other projects in JavaScript