Created
May 15, 2017 23:10
-
-
Save ernestofreyreg/8fedcc183257a529396cc479e3ed8e48 to your computer and use it in GitHub Desktop.
Create and Read contacts
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
require('dotenv').config() | |
import { MongoClient } from 'mongodb' | |
const connectMongoDB = () => MongoClient.connect(process.env.MONGODB) | |
const getContacts = (req, res) => { | |
return connectMongoDB() | |
.then( | |
db => db.collection('contacts') | |
.find({}) | |
.toArray() | |
.then(documents => ({db, documents})) | |
) | |
.then(({db, documents}) => { | |
db.close() | |
return documents | |
}) | |
.then(contacts => res.json(contacts)) | |
.catch(err => res.status(400).send(err.toString())) | |
} | |
const createContact = (req, res) => { | |
return connectMongoDB() | |
.then( | |
db => db.collection('contacts').insertOne(req.body) | |
.then(result => db) | |
) | |
.then(db => db.close()) | |
.then(() => res.json({result: 'ok'})) | |
.catch(err => res.status(400).send(err.toString())) | |
} | |
export const handler = (req, res) => { | |
if (req.method === 'POST') { | |
return createContact(req, res) | |
} | |
return getContacts(req, res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment