194831944ffe859bf95f8abe6c56498a9b1b7fd6
[motion.git] / server / api / contact / contact.controller.js
1 'use strict';
2
3 var _ = require('lodash');
4 var Contact = require('../../models').Contact;
5
6 // Get list of contacts
7 exports.index = function(req, res) {
8   Contact
9   .findAll()
10   .then(function (contacts) {
11     return res.status(200).send(contacts);
12   })
13   .catch(function(err) {
14     return handleError(res, err);
15   });
16 };
17
18 // Get a single contact
19 exports.show = function(req, res) {
20   Contact
21   .findById(req.params.id)
22   .then(function (contact) {
23     if(!contact) { return res.sendStatus(404); }
24     return res.send(contact);
25   })
26   .catch(function(err){
27     return handleError(res, err);
28   });
29 };
30
31 // Creates a new contact in the DB.
32 exports.create = function(req, res) {
33   Contact
34   .create(req.body)
35   .then(function(contact) {
36     return res.status(201).send(contact);
37   })
38   .catch(function(err) {
39     return handleError(res, err);
40   });
41 };
42
43 // Updates an existing contact in the DB.
44 exports.update = function(req, res) {
45   if(req.body.id) { delete req.body.id; }
46   Contact
47   .findById(req.params.id)
48   .then(function (contact) {
49     if(!contact) { return res.sendStatus(404); }
50     var updated = _.merge(contact, req.body);
51     updated.save()
52     .then(function () {
53       return res.status(200).send(contact);
54     })
55     .catch(function(err) {
56       return handleError(res, err);
57     });
58   })
59   .catch(function(err) {
60     return handleError(res, err);
61   });
62 };
63
64 // Deletes a contact from the DB.
65 exports.destroy = function(req, res) {
66   Contact
67   .findById(req.params.id)
68   .then(function (contact) {
69     if(!contact) { return res.sendStatus(404); }
70     contact.destroy()
71     .then(function() {
72       return res.sendStatus(204);
73     })
74     .catch(function(err) {
75       return handleError(res, err);
76     });
77   })
78   .catch(function(err) {
79     return handleError(res, err);
80   });
81 };
82
83 function handleError(res, err) {
84   return res.status(500).send(err);
85 }