I\'m a front-end dev trying to expand my horizons on a new Next project, learning Node, Mongo, and the server side of GraphQL for the first time. Apollo strikes me as the ea
Thanks to GitHub's "Used By" dropdown on the apollo-datasource-mongodb I was able to cheat off a few other repositories, and here's what I ended up with (with changes marked in comments):
const { MongoClient } = require('mongodb');
const assert = require('assert');
const { ApolloServer, gql } = require('apollo-server');
const { MongoDataSource } = require('apollo-datasource-mongodb');
// Isolated these for prominence and reuse
const dbURL = 'mongodb://localhost:27017';
const dbName = 'projectdb';
// Made each function async/await
// Swapped the datasource's findOneById() for the collection itself & standard Mongo functions
class Items extends MongoDataSource {
async getItem(id) {
return await this.collection.findOne({id: id});
}
}
const typeDefs = gql`
type Item {
id: Int!
title: String!
}
type Query {
item(id: Int!): Item
}
`;
// Made each query async/await
const resolvers = {
Query: {
item: async (_, { id }, { dataSources }) => {
return await dataSources.items.getItem(id);
},
}
}
// Move the ApolloServer constructor to its own function that takes the db
const init = (db) = {
return new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
items: new Items(db.collection('items')),
}),
});
}
// Use .connect() instead of new MongoClient
// Pass the new db to the init function defined above once it's been defined
// Call server.listen() from within MongoClient
MongoClient.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
assert.equal(null, err);
const db = client.db(dbName);
console.log(`Mongo database ${ dbName } at ${ dbURL }`);
const server = init(db);
server.listen().then(({ url }) => {
console.log(`Server ready at ${ url }`);
});
});
With these changes, the Apollo Playground at localhost:4000 works great! Now to solve the 400 error I'm getting in my client app when I query...