Skip to content

Commit 49dd673

Browse files
committed
Set up MongoDB and Reviews data source
1 parent e0e0b22 commit 49dd673

File tree

3 files changed

+28
-8
lines changed

3 files changed

+28
-8
lines changed

src/data-sources/Reviews.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { MongoDataSource } from 'apollo-datasource-mongodb'
2+
3+
export default class Reviews extends MongoDataSource {
4+
all() {
5+
return this.collection.find().toArray()
6+
}
7+
}

src/db.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { MongoClient } from 'mongodb'
2+
3+
export let db
4+
5+
const URL = 'mongodb://localhost:27017/guide'
6+
7+
const client = new MongoClient(URL, { useNewUrlParser: true })
8+
client.connect(e => {
9+
if (e) {
10+
console.error(`Failed to connect to MongoDB at ${URL}`, e)
11+
return
12+
}
13+
14+
db = client.db()
15+
})

src/index.js

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
import { ApolloServer, gql } from 'apollo-server'
22
import { getAuthIdFromJWT } from './util/auth'
3-
4-
const reviews = [
5-
{
6-
text: 'Super-duper book.',
7-
stars: 5
8-
}
9-
]
3+
import Reviews from './data-sources/Reviews'
4+
import { db } from './db'
105

116
const server = new ApolloServer({
127
typeDefs: gql`
@@ -36,7 +31,7 @@ const server = new ApolloServer({
3631
Query: {
3732
me: (_, __, context) => context.user,
3833
hello: () => '🌍🌏🌎',
39-
reviews: () => reviews
34+
reviews: (_, __, { dataSources }) => dataSources.reviews.all()
4035
},
4136
Review: {
4237
fullReview: review =>
@@ -51,6 +46,9 @@ const server = new ApolloServer({
5146
}
5247
}
5348
},
49+
dataSources: () => ({
50+
reviews: new Reviews(db.collection('reviews'))
51+
}),
5452
context: async ({ req }) => {
5553
const context = {}
5654

0 commit comments

Comments
 (0)