Home > Back-end >  Using knex to create graphql resolvers
Using knex to create graphql resolvers

Time:01-02

I am querying my database using graphQL. I am stuck on writing the graphQL resolvers to my database, using knexjs.

My problem is I want that a query or mutation to use only 1 database connection (correct me if this is wrong, but I really think this is true).

For instance, the call to the server

query {
    post {
        author
    }
}

should use 2 database calls for the post and author fields, done in a single connection to the database.

I think transactions are the way to go, and I implemented resolvers using transactions (here is a toy example):

const trxProvider = knex.transactionProvider();

const resolvers = {
    Query: {
        post: async () => {
            const trx = await trxProvider();
            let res = await trx('posts')

            return res
        },

        author: async () => {
            const trx = await trxProvider();
            let res = await trx('authors')
            return res
        }
    }
}
  1. How do I properly resolve this transaction? For instance, how would I call trx.commit() when a query/mutation has completed so the connection does not idle?

  2. Are transactions the correct approach / What knex functionality should I use so that a single database connection is used for a query mutation?

Answering any of these questions is great. Thanks!

CodePudding user response:

Connection pooling is the preferred approach. Transactions are best used to wrap multiple database writes so that all the writes can be committed or rolled back together. This avoids inconsistent writes. I've found no advantage to using transactions for reads.

I've published a tutorial that covers a lot of what you need to do with knex and GraphQL. Hopefully you'll find it helpful.

  • Related