Skip to content

Getting Started ​

Install ​

Install the package with Objection.js, Knex, and GraphQL:

sh
npm i objection-graphql-resolver objection knex graphql

The example below also uses Apollo Server, an SQLite driver, and a GraphQL client:

sh
npm i @apollo/server graphql-tag sqlite3 graphql-request

Minimal all-in-one example ​

Run the GraphQL server:

ts
// Everything is put into a single file for demonstration purposes.
//
// In real projects, you will want to separate models, typedefs,
// model resolvers, and the server into their own modules.

import type { ApolloServerOptions } from "@apollo/server"
import { ApolloServer } from "@apollo/server"
import { startStandaloneServer } from "@apollo/server/standalone"
import gql from "graphql-tag"
import Knex from "knex"
import { Model } from "objection"
import * as r from "objection-graphql-resolver"

// Define Objection.js models

class PostModel extends Model {
  static tableName = "post"

  declare id?: number
  declare text?: string
}

// Define GraphQL schema

const typeDefs = gql`
  type Post {
    id: Int!
    text: String!
  }

  type Mutation {
    create_post(text: String!): Post!
  }

  type Query {
    posts: [Post!]!
  }
`

// Map GraphQL types to model resolvers

const graph = r.graph({
  Post: r.model(PostModel),
})

// Define resolvers

const resolvers: ApolloServerOptions<any>["resolvers"] = {
  Mutation: {
    async create_post(_parent, args, context, info) {
      const post = await PostModel.query().insert(args)
      return graph.resolve(post.$query(), { context, info })
    },
  },
  Query: {
    posts(_parent, _args, context, info) {
      return graph.resolve(PostModel.query().orderBy("id"), { context, info })
    },
  },
}

// Configure database backend

const knex = Knex({ client: "sqlite3", connection: ":memory:" })
Model.knex(knex)

await knex.schema.createTable("post", post => {
  post.increments("id")
  post.text("text").notNullable()
})

// Start GraphQL server

const server = new ApolloServer({ typeDefs, resolvers })
const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
})
console.log(`Listening on ${url}`)

Query it with a GraphQL client:

ts
import { GraphQLClient } from "graphql-request"
import gql from "graphql-tag"

const client = new GraphQLClient("http://127.0.0.1:4000")

await client.request(
  gql`
    mutation create_post($text: String!) {
      new_post: create_post(text: $text) {
        id
      }
    }
  `,
  { text: "Hello, world!" },
)

const { posts } = await client.request(gql`
  query {
    posts {
      id
      text
    }
  }
`)

console.log(posts)

How it works ​

Map each GraphQL type whose objects your models load to its model with r.graph. In each root resolver, build an Objection.js query and return graph.resolve(query, { context, info }). The graph reads the fields that the client selected from info and adds the matching columns and relations to the query.

Next steps ​