Search code examples
mongodbasync-awaitgraphqlnext.jsapollo

Next JS connection with Apollo and MongoDB


I am new to Next.js and using this example from Next.js https://github.com/zeit/next.js/tree/master/examples/api-routes-apollo-server-and-client.

However, the example is silent on MongoDB integration (also I could not find any other example for the same). I have been able to make database-connection but NOT able to use it in resolvers.

My Code

pages/api/graphql.js

import { ApolloServer } from 'apollo-server-micro'
import { schema } from '../../apollo/schema'

const MongoClient = require('mongodb').MongoClient;

let db

const apolloServer = new ApolloServer({
 schema,
 context: async () => {
  if (!db) {
   try {
    const client = await MongoClient.connect(uri)
    db = await client.db('dbName')
    const post = await Posts.findOne()
    console.log(post)
   // It's working fine here
   }
   catch (e) {
     // handle any errors
   }
 }
 return { db }
 },
})

export const config = {
  api: {
    bodyParser: false,
  },
}

export default apolloServer.createHandler({ path: '/api/graphql' })

apollo/schema.js

import {makeExecutableSchema} from 'graphql-tools';
import {typeDefs} from './type-defs';
import {resolvers} from './resolvers';

export const schema = makeExecutableSchema({
    typeDefs,
    resolvers
});

apollo/resolvers.js

const Items = require('./connector').Items;
export const resolvers = {
    Query: {
        viewer(_parent, _args, _context, _info) {
            //want to populate values here, using database connection
            return { id: 1, name: 'John Smith', status: 'cached' }
        },
        ...
    }
}

I am stuck in the resolvers.js part. Don't know how to get the cached database connection inside resolvers.js. If I create a new database connection file, top-level await is not supported there, so how do I proceed?


Solution

  • If context is a function, whatever you return from the function will be available as the context parameter in your resolver. So if you're returning { db }, that's what your context parameter will be -- in other words, you can access it as context.db inside your resolver.