Skip to content

Instantly share code, notes, and snippets.

@alexandr-g
Created June 11, 2020 15:56
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/47f4ebf3e772c5a6d25a66f3598a1d49 to your computer and use it in GitHub Desktop.
Save alexandr-g/47f4ebf3e772c5a6d25a66f3598a1d49 to your computer and use it in GitHub Desktop.
Sharing schema between Apollo Client and Apollo Server
// pages/api/graphql.js
import { ApolloServer, gql } from 'apollo-server-micro'
import { makeExecutableSchema } from 'graphql-tools'
import { MongoClient } from 'mongodb'
require('dotenv').config()
const typeDefs = gql`
type User {
id: ID!
firstName: String!
lastName: String!
blog: String
stars: Int
}
type Query {
users: [User]!
}
`
const resolvers = {
Query: {
users(_parent, _args, _context, _info) {
return _context.db
.collection('users')
.findOne()
.then((data) => {
return data.users
})
},
},
}
const schema = makeExecutableSchema({
typeDefs,
resolvers,
})
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