gkr

graphql-knex-resolver

GraphQL Resolver built with Knex

Showing:

Popularity

Downloads/wk

1

Maintenance

No Maintenance Data Available

Package

Dependencies

2

License

MIT

Type Definitions

Tree-Shakeable

No?

Categories

Readme

graphql-knex-resolver

NPM version Build status Dependency Status Code Climate

GraphQL Resolver built with Knex. Can be used to parse GraphQL ASTs into SQL, and as a resolver method standin in a GraphQL schema. Supports whichever databases are supported by Knex.

Install

$ npm install --save graphql-knex-resolver

Usage

Do the stuff you'd normally do, but use the provided resolver method in your GraphQL schema.

1. Initialize the Resolver

const Resolver = require('graphql-knex-resolver')

// setup knex
const gql = require('graphql')
const knex = require('knex')({
  client: 'pg',
  connection: {
    // ...
  }
})
const resolver = Resolver.getResolver(knex)

2. Define the Schema

// create the GraphQL schema using the resolver
const userObject = new gql.GraphQLObjectType({
  name: 'User',
  fields: () => ({
    username: {
      type: gql.GraphQLString
    }
  })
})
const userQuery = new gql.GraphQLObjectType({
  name: 'UserQuery',
  fields: () => ({
    user: {
      type: userObject,
      resolve: resolver // <-------- use the resolver method
    }
  })
})
const userSchema = new gql.GraphQLSchema({
  query: userQuery
})

3. Execute a Query

const findUserByUsername = `{
  user (username: $username) {
    id
    username
  }
}`
return gql.graphql(userSchema, findUserByUsername, {
    username: "tjwebb"
  })
  .then(results => {
    console.log(results)
    // results = {
    //   data: {
    //     user: {
    //       username: 'tjwebb'
    //     }
    //   }
    // }
  })

API

getResolver(engine)

Prepare a new GraphQL Query Resolver

.toSQL(query, dialect, args)

Translates a GraphQL query into SQL, irrespective of schema. Uses the root field name as the table.

dialect is one of (docs):

  • pg
  • mysql
  • sqlite3
  • oracle
  • mariasql

Example

Using the findUserByUsername query above:

Simple Select Statement
const sql = resolver.toSQL(findUserByUsername, 'pg', {
  username: 'tjwebb'
})
// sql = select "username", from "user" where "name" = 'tjwebb'
Select Where In List Statement
const sql = resolver.toSQL(queries.parameterizedWithListType, 'pg', {
  username: [ 'tjwebb', 'admin' ]
})
// sql = select "username" from "user" where "name" = ANY ('{"tjwebb","admin"}')

Table name is inferred to be user since the root field is user. The following query would use the table name "foo":

const findUserByUsername = `{
  foo (username: $username) {
    id
    username
  }
}`

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial