Last active
May 17, 2017 20:12
-
-
Save ernestofreyreg/8de71071c43b6729586413804ae29feb to your computer and use it in GitHub Desktop.
Async microrouter version
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' | |
import { get, post, router } from 'microrouter' | |
const connectMongoDB = () => MongoClient.connect(process.env.MONGODB) | |
const getContacts = async (req, res) => { | |
const db = await connectMongoDB() | |
const contacts = await db.collection('contacts').find({}).toArray() | |
db.close() | |
return res.json(contacts) | |
} | |
const createContact = async (req, res) => { | |
const db = await connectMongoDB() | |
await db.collection('contacts').insertOne(req.body) | |
db.close() | |
return res.json({result: 'ok'}) | |
} | |
export const handler = router( | |
get('/api/contacts', getContacts), | |
post('/api/contacts/create', createContact), | |
(req, res) => res.json({status: 'ok'}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment