Skip to content

Instantly share code, notes, and snippets.

@alexandr-g
Created June 11, 2020 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandr-g/a5b1f030ffe8489b8e98b68d0e434f43 to your computer and use it in GitHub Desktop.
Save alexandr-g/a5b1f030ffe8489b8e98b68d0e434f43 to your computer and use it in GitHub Desktop.
pages/api/graphql.js
// pages/api/graphql.js
import { ApolloServer } from 'apollo-server-micro'
import { MongoClient } from 'mongodb'
import { schema } from '../../apollo/schema'
require('dotenv').config()
let db
const apolloServer = new ApolloServer({
schema,
context: async () => {
if (!db) {
try {
const dbClient = new MongoClient(process.env.MONGO_DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
if (!dbClient.isConnected()) await dbClient.connect()
db = dbClient.db('next-graphql')
} catch (e) {
console.log('--->error while connecting with graphql context (db)', e)
}
}
return { db }
},
})
export const config = {
api: {
bodyParser: false,
},
}
export default apolloServer.createHandler({ path: '/api/graphql' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment