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.
$ npm install --save graphql-knex-resolver
Do the stuff you'd normally do, but use the provided resolver method in your GraphQL schema.
const Resolver = require('graphql-knex-resolver')
// setup knex
const gql = require('graphql')
const knex = require('knex')({
client: 'pg',
connection: {
// ...
}
})
const resolver = new Resolver(knex)
// create the GraphQL schema using the resolver
const User = new gql.GraphQLObjectType({
name: 'User',
fields: () => ({
id: {
type: gql.GraphQLID
},
username: {
type: gql.GraphQLString
},
roles: {
type: new gql.GraphQLList(Role),
resolve: resolver.relation({
foreignKey: 'user_id'
})
}
})
})
const Role = new gql.GraphQLObjectType({
name: 'Role',
fields: () => ({
id: {
type: gql.GraphQLID
},
name: {
type: gql.GraphQLString
}
})
})
const schema = new gql.GraphQLSchema({
query: new gql.GraphQLObjectType({
name: 'Query',
fields: () => ({
user: {
type: User,
resolve: resolver.object(),
args: {
// ...
}
},
role: {
type: Role,
resolve: resolver.object(),
args: {
// ...
}
}
})
})
})
const findUserByUsername = `{
user (username: $username) {
username
roles {
name
}
}
}`
return gql.graphql(userSchema, findUserByUsername, {
username: "tjwebb"
})
.then(results => {
console.log(results)
// results = {
// data: {
// user: {
// username: 'tjwebb',
// roles: [
// { name: 'admin' }
// ]
// }
// }
// }
})
Prepare a new GraphQL Query Resolver
Return an object resolver
Return a relation resolver.
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
Using the findUserByUsername
query above:
const sql = resolver.toSQL(findUserByUsername, 'pg', {
username: 'tjwebb'
})
// sql = select "username", from "user" where "name" = 'tjwebb'
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
}
}`