0

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?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.