Skip to content

Instantly share code, notes, and snippets.

@francisbrito
Created January 25, 2016 16:53
Show Gist options
  • Save francisbrito/8abe4e08ef0a7c7923c7 to your computer and use it in GitHub Desktop.
Save francisbrito/8abe4e08ef0a7c7923c7 to your computer and use it in GitHub Desktop.
/**
* 3rd party imports.
*/
var express = require('express');
var mongodb = require('mongodb');
/**
* Local imports.
*/
var router = new express.Router();
var dbConnection = mongodb.MongoClient.connect('mongodb://localhost/test');
router.get('/', (request, response) => {
Promise
.resolve(dbConnection)
.catch( error => response.status(500).send(error.message) )
.then( db => db.collection('todos').find() )
.then( cursor => cursor.toArray() )
.then( todos => response.send(todos) )
});
router.get('/:todoId', (request, response) => {
// TODO: try-parse?
var rawTodoId = request.params.todoId;
var todoId = new mongodb.ObjectId(rawTodoId);
Promise
.resolve(dbConnection)
.catch( error => response.status(500).send(error.message) )
.then( db => db.collection('todos').findOne(todoId) )
.then( todo => {
if (!todo) return response.status(404).send('todo not found');
response.send(todo);
} )
});
router.post('/', (request, response) => {
var text = request.body.text;
if (!text) return response.status(400).send('`text` is missing.');
Promise
.resolve(dbConnection)
.catch( error => response.status(500).send(error.message) )
.then( db => db.collection('todos').insert({text: text, done: false}) )
.then( result => response.send(result.ops[0]) );
});
router.delete('/:todoId', (request, response) => {
// TODO: try-parse?
var rawTodoId = request.params.todoId;
var todoId = new mongodb.ObjectId(rawTodoId);
Promise
.resolve(dbConnection)
.catch( error => response.status(500).send(error.message) )
.then( db => db.collection('todos').deleteOne({_id: todoId}) )
.then( result => response.send(result) );
});
router.patch('/:todoId', (request, response) => {
// TODO: try-parse?
var rawTodoId = request.params.todoId;
var todoId = new mongodb.ObjectId(rawTodoId);
var newFields = request.body;
Promise
.resolve(dbConnection)
.catch( error => response.status(500).send(error.message) )
.then( db => db.collection('todos').update({_id: todoId}, {$set: newFields}) )
.then( result => response.send(result) );
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment