Thanks Trevor, 5 minutes after I posted, I got it running!
This seems to work, saves and queries a simple employee doc {first Name, LastName} using mongodb data source package. Can you review and let me know if I did anything egregious?
Thanks,
Roy
const { ApolloServer } = require(“@apollo/server”);
const { startStandaloneServer } = require(‘@apollo/server/standalone’);
const { MongoDataSource } = require(“apollo-datasource-mongodb”);
const mongoose = require(“mongoose”);
const typeDefs = #graphql type Employee { firstName: String lastName: String } type Query { employees: [Employee] } type Mutation { CreateEmployee(firstName: String!, lastName: String!): Employee }
;
const EmployeeModel = mongoose.model(“Employee”, {
firstName: String,
lastName: String,
});
const resolvers = {
Query: {
employees: (, __, contextValue) => {
return contextValue.dataSources.employees.getEmployees()
},
},
Mutation: {
CreateEmployee: (, args, contextValue) => {
return contextValue.dataSources.employees.createEmployee(args)
},
},
};
class Employees extends MongoDataSource {
constructor(options) {
super(options);
this.initialize({ cache: options.cache, context: options.token });
}
async getEmployees() {
return await this.model.find();
}
async createEmployee(args) {
return await this.model.create(args);
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
});
const MONGODB_URL = “mongodb://127.0.0.1:27017/test”;
async function connectMongodb() {
await mongoose.connect(MONGODB_URL);
console.log(“Connected to database successfully ”);
}
(async () => {
// Connect to DB
try {
await connectMongodb();
} catch (e) {
console.error(e);
throw new Error(Unable to connect to database
);
}
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
context: async ({req}) => {
const { cache } =server;
const token = req.headers.token;
return {
dataSources: {
employees: new Employees(EmployeeModel),
},
token,
};
},
});
console.log(🚀 Server ready at ${url}
);
})();