2014-12-10 16:28:16 +03:00
|
|
|
var config = require('../config'),
|
2014-09-26 17:31:23 +04:00
|
|
|
Promise = require('bluebird'),
|
2014-07-15 14:40:14 +04:00
|
|
|
fs = require('fs-extra'),
|
2016-03-30 06:31:31 +03:00
|
|
|
pUnlink = Promise.promisify(fs.unlink),
|
2014-07-15 14:40:14 +04:00
|
|
|
storage = require('../storage'),
|
|
|
|
errors = require('../errors'),
|
2014-12-10 16:28:16 +03:00
|
|
|
utils = require('./utils'),
|
2015-11-12 15:29:45 +03:00
|
|
|
i18n = require('../i18n'),
|
2014-07-15 14:40:14 +04:00
|
|
|
|
|
|
|
upload;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ## Upload API Methods
|
|
|
|
*
|
|
|
|
* **See:** [API Methods](index.js.html#api%20methods)
|
|
|
|
*/
|
|
|
|
upload = {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ### Add Image
|
|
|
|
*
|
|
|
|
* @public
|
|
|
|
* @param {{context}} options
|
2016-03-30 06:31:31 +03:00
|
|
|
* @returns {Promise<String>} location of uploaded file
|
2014-07-15 14:40:14 +04:00
|
|
|
*/
|
2016-03-30 06:31:31 +03:00
|
|
|
add: Promise.method(function (options) {
|
|
|
|
var store = storage.getStorage();
|
|
|
|
|
|
|
|
// Public interface of the storage module's `save` method requires
|
|
|
|
// the file's name to be on the .name property.
|
|
|
|
options.name = options.originalname;
|
|
|
|
options.type = options.mimetype;
|
2014-07-15 14:40:14 +04:00
|
|
|
|
2014-12-10 16:28:16 +03:00
|
|
|
// Check if a file was provided
|
2016-03-30 06:31:31 +03:00
|
|
|
if (!utils.checkFileExists(options)) {
|
|
|
|
throw new errors.NoPermissionError(i18n.t('errors.api.upload.pleaseSelectImage'));
|
2014-07-15 14:40:14 +04:00
|
|
|
}
|
|
|
|
|
2014-12-10 16:28:16 +03:00
|
|
|
// Check if the file is valid
|
2016-03-30 06:31:31 +03:00
|
|
|
if (!utils.checkFileIsValid(options, config.uploads.contentTypes, config.uploads.extensions)) {
|
|
|
|
throw new errors.UnsupportedMediaTypeError(i18n.t('errors.api.upload.pleaseSelectValidImage'));
|
2014-12-10 16:28:16 +03:00
|
|
|
}
|
|
|
|
|
2016-03-30 06:31:31 +03:00
|
|
|
return store.save(options).finally(function () {
|
2014-07-15 14:40:14 +04:00
|
|
|
// Remove uploaded file from tmp location
|
2016-03-30 06:31:31 +03:00
|
|
|
return pUnlink(options.path);
|
2014-07-15 14:40:14 +04:00
|
|
|
});
|
2016-03-30 06:31:31 +03:00
|
|
|
})
|
2014-07-15 14:40:14 +04:00
|
|
|
};
|
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
module.exports = upload;
|