Built motion from commit 5e31ea4.|0.0.32
[motion.git] / server / api / mail_attachment / mail_attachment.controller.js
1 'use strict';
2
3 var _ = require('lodash');
4 var path = require('path');
5 var fs = require('fs');
6 var formidable = require('formidable');
7 var Promise = require('bluebird');
8
9 var config = require('../../config/environment');
10 var MailAttachment = require('../../models').MailAttachment;
11
12 // Get list of mailAttachments
13 exports.index = function (req, res, next) {
14   MailAttachment
15     .findAll()
16     .then(function (mailAttachments) {
17       return res.status(200).send(mailAttachments);
18     })
19     .catch(function (err) {
20       return next(err);
21     });
22 };
23
24 // Get a single mailAttachment
25 exports.show = function (req, res, next) {
26   MailAttachment
27     .findById(req.params.id)
28     .then(function (mailAttachment) {
29       res.download(mailAttachment.path, mailAttachment.fileName);
30     })
31     .catch(function (err) {
32       return next(err);
33     });
34 };
35
36 // Creates a new mailAttachment in the DB.
37 exports.create = function (req, res, next) {
38
39   var form = new formidable.IncomingForm();
40   form.uploadDir = path.join(config.root, 'server', 'files', 'attachments');
41   form.keepExtensions = true;
42   form.multiples = true;
43   form.hash = true;
44
45   form.parse(req, function (err, form, wrap) {
46     if (err) {
47       return res.status(500).send(err);
48     }
49     return res.status(201).send({
50       size: wrap.file.size,
51       path: wrap.file.path,
52       name: wrap.file.name,
53       type: wrap.file.type,
54       basename: path.basename(wrap.file.path)
55     });
56   });
57 };
58
59 // Updates an existing mailAttachment in the DB.
60 exports.update = function (req, res, next) {
61   if (req.body.id) {
62     delete req.body.id;
63   }
64   MailAttachment
65     .findById(req.params.id)
66     .then(function (mailAttachment) {
67       if (!mailAttachment) {
68         return res.sendStatus(404);
69       }
70       var updated = _.merge(mailAttachment, req.body);
71       updated.save()
72         .then(function () {
73           return res.status(200).send(mailAttachment);
74         })
75         .catch(function (err) {
76           return next(err);
77         });
78     })
79     .catch(function (err) {
80       return next(err);
81     });
82 };
83
84 // Deletes a mailAttachment from the DB.
85 exports.destroy = function (req, res, next) {
86   var unlink = Promise.promisify(require("fs").unlink);
87   var _path = path.join(config.root, 'server', 'files', 'attachments', req.params.id);
88
89   return unlink(_path)
90     .then(function () {
91       return res.sendStatus(204);
92     })
93     .catch(function (err) {
94       return handleError(res, err);
95     });
96 };
97
98 function handleError(res, err) {
99   return res.status(500).send(err);
100 }