Created
June 11, 2020 15:56
-
-
Save alexandr-g/47f4ebf3e772c5a6d25a66f3598a1d49 to your computer and use it in GitHub Desktop.
Sharing schema between Apollo Client and Apollo Server
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, 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