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

graphios

v1.2.1

Published

Easy-to-use HTTP client for GraphQL API's

Downloads

9

Readme

Graphios

Easy-to-use Axios-based HTTP client for GraphQL API's. This library is more suitable for back-end interactions with GraphQL servers (not frontends/UI's). The Auto-pagination feature allows fetching of large amounts of data from paginated GraphQL API's without the need to write custom code.

Features:

  • Simple API focused on GraphQL use case.
  • Auto-pagination (Relay pattern only, such as Github API)
  • Event listener for paginated requests
  • Configurable retries (and retryDelay)

Installing

Using npm:

$ npm install graphios

Using yarn:

$ yarn add graphios

Configuration object (input)

interface Config {
  url: string // graphQL endpoint
  query: string // graphQl query
  headers?: object // Optional headers object
  timeout?: number // Optional custom timeout in ms (default to no timeout)
  retries?: number // Optional retries (default to 3)
  retryDelay?: number // Optional retryDelay in ms (default to 500)
  pagination?: boolean // Optional Auto-pagination (default to false)
  requestId?: string // Optional request identifier, useful for monitoring page iterations
  pageDelay?: number // Optional delay between pagination iterations in ms (default to 200)
}

Response object (output)

interface GraphiosResponse {
  data: object // Response data
  status?: number // not present on auto-paginated requests
  statusText?: string // not present on auto-paginated requests
  headers?: object // not present on auto-paginated requests
  pagesProcessed?: number // Only available for auto-paginated requests
}

Examples

Performing a simple query:

import { graphios } from 'graphios';

const query = `{
  users {
    firstName
    email
  }
}`

// using promises
graphios({
    query,
    url: 'https://mygraphql.xyz/graphql'
  })
  .then( response => {
    // handle success
    console.log(response.data);
  })
  .catch( error => {
    // handle error
    console.log(error);
  })

// Using async/await
(async () => {
  try {
    const response = await graphios({
    query,
    url: 'https://mygraphql.xyz/graphql',
  })
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
})()

Performing a paginated query

For auto-pagination support, a $cursor variable should be included in the query. The API server must follow the relay pagination pattern using nodes and edges. The paginated query is not required to be on the first level, but only one pagination query is allowed per request.

Example using an usable query for the Github API

// import graphiosEvents for pagination events
import { graphios, graphiosEvents } from 'graphios';

// A query variable $cursor is required.
const query = `
  query Repository($cursor:String){
    organization(login:"microsoft"){
      membersWithRole(first:100, after:$cursor){
        edges {
          node {
            name
          }
        }
        pageInfo {
          endCursor
          hasNextPage
        }
      }
    }
  }
`

const headers = {
    'authorization': `Bearer 1234567SuperHardKey8910`
  }

// using promises
graphios({
    query,
    url: 'https://api.github.com/graphql',
    headers,
    retries: 3,
    retryDelay: 500,
    pagination: true,
    requestId: 'myRepoReq123'
    pageDelay: 100
  })
  .then( response => {
    // handle success
    console.log(response.data);
  })
  .catch( error => {
    // If any page fails, it will end here
    console.log(error);
  })

// Using async/await
(async () => {
  try {
    const response = await graphios({
    query,
    url: 'https://api.github.com/graphql',
    headers,
    retries: 3,
    retryDelay: 500
    pagination: true,
    requestId: 'myRepoReq123',
    pageDelay: 100
  })
    console.log(response.data);

  } catch (error) {
    // If any page fails, it will end here
    console.error(error);
  }
})()

// Optional pagination event handler
graphiosEvents.on('pagination', pageData => {
  console.log(
  pageData.page // Page number,
  pageData.response, // Response object, same as an individual request
  pageData.requestId // Request identifier set on the config: 'myRepoReq123'
})

Axios custom configuration (optional input)

An optional second object can be passed if any specific configuration from Axios is needed. This will override any configuration made on the graphios config (first parameter).

interface AxiosRequestConfig {
  url?: string
  method?: Method
  baseURL?: string
  transformRequest?: AxiosTransformer | AxiosTransformer[]
  transformResponse?: AxiosTransformer | AxiosTransformer[]
  headers?: any
  params?: any
  paramsSerializer?: (params: any) => string
  data?: any
  timeout?: number
  withCredentials?: boolean
  adapter?: AxiosAdapter
  auth?: AxiosBasicCredentials
  responseType?: ResponseType
  xsrfCookieName?: string
  xsrfHeaderName?: string
  onUploadProgress?: (progressEvent: any) => void
  onDownloadProgress?: (progressEvent: any) => void
  maxContentLength?: number
  validateStatus?: (status: number) => boolean
  maxRedirects?: number
  socketPath?: string | null
  httpAgent?: any
  httpsAgent?: any
  proxy?: AxiosProxyConfig | false
  cancelToken?: CancelToken
}

Example:

graphios(
  {
    query: `{ Users { name } }`,
    url: 'https://mygraphql.xyz/graphql'
  },
  {
    maxRedirects: 10
  }
)
  .then( response => {
    // handle success
    console.log(response.data)
  })
  .catch( error => {
    // If any page fails, it will end here
    console.log(error)
  })

Credits

Relies on the excellent work provided by axios and axios-retry.

License

MIT