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

graphql-cursor-sql-helper

v0.1.0

Published

helper for building graphql relay compatible schema with sql db

Downloads

9

Readme

GraphQl cursor SQL pagination helper for relay compatible schema

:purple_heart: :blue_heart: :purple_heart: Made with Love by Kuba Svehla :purple_heart: :blue_heart: :purple_heart:

Motivation

This library is the extension of awesome graphql-relay-js which solve problem how simply implement cursor pagination to your SQL's dbs query without special magic.

If you're creating GraphQl schema which is compatible with relay cursor pagination (cursor pagination spec ). You probably use graphql-relay-js library for helper functions to define your schema.

Problem with graphql-relay-js is that functions like connectionFromArray(...) works on application javascript layer. That means that process of pagination is inefficient and it takes too much RAM & CPU power.

This library solve how to recalculate Pagination args (first & after & last & before) to SQL's OFFSET LIMIT params.

Another benefits

We added totalCount field to graphQl schema. At the moment graphql-relay-js does not implement it yet. We decided that totalCount is productive for and you have option to set it.

Why is not totalCount in graphql-relay-js (issue)

If you want to enable totalCount you have to set it to your connectionDefinition like in example:

connectionDefinitions({
  name: 'User',
  nodeType: UserType,
  // adding connectionFields to type
  // is necessary for querying totalCount in graphQl
  connectionFields: {
    totalCount: { type: new GraphQLNonNull(GraphQLInt) }
  }
}).connectionType,

note1: connectionField param of connectionDefinition is not documented in readme yet. But you can find implementation here: implemenation of connectionFields in relay-graphql-js

note2: first param is meaning last added nodes -> not first positions in array

So if you select

first 3 items from 50 it generate:

  • offset: 0
  • limit: 3

last 3 items from 50 it generate:

  • offset: 47
  • limit: 3

Instalation

yarn add graphql-cursor-sql-helper

or

npm install graphql-cursor-sql-helper

API

library provide this function:

  • connectionToSqlQuery

connectionToSqlQuery(...)

Params

  • totalCount - count of line for whole SQL SELECT
  • paginationArgs - provided from connectionArgs fn from graphql-relay-js
  • callbackWithValues - callback return object with offset and limit computed values

return

  • Connection with sql results & totalCount

Example

Raw function API example

// graphql resolver
// ...
return connectionToSqlQuery(
  // this return totalCount for current select
  await someOrmSqlModel.getTotalCount(), 
  paginationArgs,
  // get computed values for sql pagination
  ({ offset, limit }) => (
    // applying it to sql select for native sql pagination
    someOrmSqlModel.getData({ offset, limit })
  )
)

Example with graphQl resolver for users

import { connectionToSqlQuery } from 'graphql-cursor-sql-helper'
/*
    _          _                              _          _  
  >(')____,  >(')____,   ... some code ...  >(')____,  >(') ___, 
    (` =~~/    (` =~~/   ... some code ...   (` =~~/    (` =~~/ 
~^~~^~^`---'~^~^~^`---'~^~^~^`---'~^~^~^`---'~^~^~^`---'~^~^~ 
*/
const Admin = new GraphQLObjectType({
  name: 'Admin',
  description: '...',
  interfaces: [nodeInterface],
  isTypeOf: obj => instanceof sqlModelAdmin,
  fields: () => ({
    /*
       _          _                              _          _  
     >(')____,  >(')____,   ... some code ...  >(')____,  >(') ___, 
       (` =~~/    (` =~~/   ... some code ...   (` =~~/    (` =~~/ 
    ~^~~^~^`---'~^~^~^`---'~^~^~^`---'~^~^~^`---'~^~^~^`---'~^~^~ 
    */
    users: {
      type: connectionDefinitions({
        name: 'User',
        nodeType: UserType,
        // adding connectionFields to type
        // is necessary for quering totalCount in graphQl
        connectionFields: {
          totalCount: { type: new GraphQLNonNull(GraphQLInt) }
        }
      }).connectionType,
      args: connectionArgs,
      description: `...`,
      resolve: async (parent, paginationArgs) => {
        // call `graphql-sql-cursor-helper` function for calculating real OFFSET & LIMIT
        return connectionToSqlQuery(
          await someOrmSqlModel.getTotalCount(), // <- this 
          paginationArgs,
          // get computed values for sql pagination
          ({ offset, limit }) => (
            // applying it to sql select for native sql pagination
            someOrmSqlModel.getUsers({ offset, limit })
          )
        )
      }
    }
  })
})

## Contributing

After cloning this repo, ensure dependencies are installed by running:

npm install or yarn

Develop by

yarn run start or npm run start

Test changes by

yarn run test or npm run test