Created
June 11, 2020 16:00
-
-
Save alexandr-g/a5b1f030ffe8489b8e98b68d0e434f43 to your computer and use it in GitHub Desktop.
pages/api/graphql.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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