3 var _ = require('lodash');
4 var path = require('path');
5 var fs = require('fs');
6 var formidable = require('formidable');
7 var Promise = require('bluebird');
9 var config = require('../../config/environment');
10 var MailAttachment = require('../../models').MailAttachment;
12 // Get list of mailAttachments
13 exports.index = function (req, res, next) {
16 .then(function (mailAttachments) {
17 return res.status(200).send(mailAttachments);
19 .catch(function (err) {
24 // Get a single mailAttachment
25 exports.show = function (req, res, next) {
27 .findById(req.params.id)
28 .then(function (mailAttachment) {
29 res.download(mailAttachment.path, mailAttachment.fileName);
31 .catch(function (err) {
36 // Creates a new mailAttachment in the DB.
37 exports.create = function (req, res, next) {
39 var form = new formidable.IncomingForm();
40 form.uploadDir = path.join(config.root, 'server', 'files', 'attachments');
41 form.keepExtensions = true;
42 form.multiples = true;
45 form.parse(req, function (err, form, wrap) {
47 return res.status(500).send(err);
49 return res.status(201).send({
54 basename: path.basename(wrap.file.path)
59 // Updates an existing mailAttachment in the DB.
60 exports.update = function (req, res, next) {
65 .findById(req.params.id)
66 .then(function (mailAttachment) {
67 if (!mailAttachment) {
68 return res.sendStatus(404);
70 var updated = _.merge(mailAttachment, req.body);
73 return res.status(200).send(mailAttachment);
75 .catch(function (err) {
79 .catch(function (err) {
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);
91 return res.sendStatus(204);
93 .catch(function (err) {
94 return handleError(res, err);
98 function handleError(res, err) {
99 return res.status(500).send(err);