Created
July 30, 2018 13:34
-
-
Save krivaten/359f067bcd0a5154c54c3335014b3ecd to your computer and use it in GitHub Desktop.
A Netlify Lambda Function for that uses Apollo GraphQL
This file contains hidden or 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
const { ApolloServer, gql } = require('apollo-server-lambda'); | |
const MongoClient= require('mongodb/lib/mongo_client'); | |
if (process.env.NODE_ENV !== 'production') { | |
require('dotenv').load() | |
} | |
const DB_URI = process.env.DB_URI | |
const DB_NAME = process.env.DB_NAME | |
exports.handler = async function() { | |
const client = await MongoClient.connect(DB_URI) | |
const db = client.db(DB_NAME) | |
const Posts = db.collection('posts') | |
const typeDefs = gql` | |
type Query { | |
post: Post | |
posts: [Post] | |
} | |
type Post { | |
_id: String! | |
title: String! | |
content: String! | |
comments: [Comment] | |
} | |
`; | |
const resolvers = { | |
Query: { | |
post: async (root, { _id }) => { | |
return await Posts.findOne(_id) | |
}, | |
posts: async () => { | |
return await Posts.find({}).toArray() | |
} | |
}, | |
Mutation: { | |
createPost: async (root, args) => { | |
const res = await Posts.insert(args) | |
return await Posts.findOne({ _id: res.insertedIds[1] }) | |
} | |
} | |
}; | |
const server = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
}); | |
const handler = server.createHandler(); | |
return handler(...arguments); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment