npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fabienjuif/graph-client

v0.5.1

Published

light zero dependency graphql-client, supporting cache and SSR

Downloads

8

Readme

@fabienjuif/graph-client

light zero dependency graphql-client, supporting cache and SSR

CircleCI npm bundle size (scoped) npm (scoped) GitHub Coveralls github

Features

  • Light (bundlesize)
  • Supports browser and Node (SSR compatible)
  • Supports cache (via third party library, or your own code)
    • cache is not used for mutations
    • cache can be disabled per request with noCache: true option

Install

npm install --save @fabienjuif/graph-client

API

import createClient from '@fabienjuif/graph-client'

  • createClient(options: object): Client: creates and returns a new graphql client
    • options.url: (required), the graphql endpoint to query
    • options.cache: (optional, default = undefined), the cache implementation to use, it must implement set(key: string, value: object) and get(key: string): object to be compatible. You can use a Map or lru package for example.
    • options.token: (optional, default = undefined) will be used to add an authorization header, can be:
      • a ̀string: in which cache it will the client will add Bearer in front of it
      • a function:
        • if the function returns a Promise, the client will wait the promise to resolve, then add Bearer before the returned value. Attention, your query will not be send to your graphql API until the promise is resolved!
        • in other cases, the Bearer is added to the returned value
    • options.logger: (optional, default = console), the logger to user, it can implement logger.trace(value: any) or logger('trace', value: any) and will be used to log errors if found
    • options.headers: (optional; default = {}), the headers to set to http requests

const graphql = createClient(**options**)

  • graphql.setHeaders(param: function|object):
    • if param is a function it will be called with the previous headers and the returned value will be used as new headers
    • in other cases param will be used as new headers
  • graphql(query: string, variables: object, options: object): Promise: will query your endpoint and returns the data part
    • if cache is set it will be used, and if an entry is found it will be returned without calling the API
    • if the query is a mutation, the cache will not be used
    • if options.noCache is set to true the cache, even if it exists, will not be used

Usage / Examples

Minimum

This is minimal informations you have to give to use this lib. In this case, the client does not use cache.

import createClient from '@fabienjuif/graph-client'

const graphql = createClient({
  url: 'https://my-domain/graphql',
})

const QUERY = `
query GetUser($id: String!) {
  user (id: $id) {
    id
    name
    email
  }
}
`

graphql(QUERY, { id: '2' })
  .then(data => console.log(data))

LRU cache

In this example, the client will use a cache from an external library (here lru).

import LRU from 'lru'
import createClient from '@fabienjuif/graph-client'

const graphql = createClient({
  url: 'http://my-domain.com/graphql'
  cache: new LRU(100), // max 100 items
})

const QUERY = `
query getUser($id: String!) {
  user(id: $id) {
    id
    name
    email
  }
}
`
const run = async () => {
  // first call will set the result into the cache
  // the cache key is a composition of your query and variables
  // both should be serializable
  const { user } = await graphql(QUERY, { id: '2' })
  console.log(user)

  // second call will use cache instead of quering the database
  const { user: user2 } = await graphql(QUERY, { id: '2' })
  console.log(user2)

  // third call will call your endpoint because variables are differents
  // a new entry will be added to the cache
  const { user: user3 } = await graphql(QUERY, { id: '3' })
  console.log(user3)
}
run()

Map cache

In this example, the client will use a javascript Map as a cache.

import createClient from '@fabienjuif/graph-client'

const graphql = createClient({
  url: 'http://my-domain.com/graphql'
  cache: new Map(),
})

const QUERY = `
query getUser($id: String!) {
  user(id: $id) {
    id
    name
    email
  }
}
`
const run = async () => {
  // first call will set the result into the cache
  // the cache key is a composition of your query and variables
  // both should be serializable
  const { user } = await graphql(QUERY, { id: '2' })
  console.log(user)

  // second call will use cache instead of quering the database
  const { user: user2 } = await graphql(QUERY, { id: '2' })
  console.log(user2)

  // third call will call your endpoint because variables are differents
  // a new entry will be added to the cache
  const { user: user3 } = await graphql(QUERY, { id: '3' })
  console.log(user3)
}
run()

Disable cache for specific queries

In this example cache is set from a javascript Map. The cache will not be used for one of the request, even if the cache is set and the query is a graphql query (not a mutation).

import createClient from '@fabienjuif/graph-client'

const graphql = createClient({
  url: 'https://my-domain/graphql',
  cache: new Map(), // use a Javascript map as cache
})

const CACHED_QUERY = `
query GetUser($id: String!) {
  user (id: $id) {
    id
    name
    email
  }
}
`

// this request will be cached
graphql(CACHED_QUERY, { id: '2' })
  .then(data => console.log(data))

const QUERY = `
query GetTopics($max: Int!) {
  topics (max: $max) {
    id
    title
  }
}
`

// this request will NOT be cached because we ask not to use it in request scope
// even if the cache is specified in the factory
graphql(QUERY, { max: 10 }, { noCache: true })
  .then(data => console.log(data))

Set a token

In this example the token is retrieved from the localStorage for each request. If the token does not exists then the Authorization header will not be set

import createClient from '@fabienjuif/graph-client'

const getToken = () => localStorage.getItem('token')

const graphql = createClient({
  url: 'https://my-domain/graphql',
  token: getToken, // token can also be a string, or a function that returns a promise
})

const run = async () => {
  // set a token
  localStorage.setItem('token', 'my-token')

  // first call the Authorization header is set:
  //  - Authorization: Bearer my-token
  const { user } = await graphql(QUERY, { id: '2' })
  console.log(user)

  // remove the token
  localStorage.removeItem('token')

  // second call the Authorization header is not set
  const { user: user2 } = await graphql(QUERY, { id: '2' })
  console.log(user2)
}
run()