npm.io
7.7.1 • Published 48m ago

objection-graphql-resolver

Licence
MIT
Version
7.7.1
Deps
1
Size
63 kB
Vulns
0
Weekly
0
Stars
18

objection-graphql-resolver

A helper library to resolve GraphQL queries directly with Objection.js models and relations.

  • Selects the columns and relations that the GraphQL query asks for, using withGraphFetched.
  • Resolves relations nested to any depth by traversing relationMappings.
  • Paginates root queries and to-many relations with a cursor.
  • Resolves model getters the same way as database columns.
  • Filters queries with GraphQL arguments like { date: "2020-10-01", category__in: ["News", "Politics"] }.
  • Limits the exposed fields, restricts rows with query modifiers, and post-processes field values per viewer.

Note that there is a sister project: orchid-graphql which does the same for Orchid ORM.

See the documentation.

Install

npm i objection-graphql-resolver objection knex graphql

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

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

Minimal all-in-one example

Run the GraphQL server:

// 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:

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)