-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
53 lines (48 loc) · 1.57 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Created by gaurav on 17/5/16.
*/
/**
* A simple storage engine
* */
function CloudinaryStorage (opts) {
if(opts && opts.cloudinary){
// Checking to see if opts.cloudinary.cloudinary is present for backwards compatibility
// even though opts.cloudinary is the correct way to pass.
this.cloudinary = opts.cloudinary.cloudinary ? opts.cloudinary.cloudinary : opts.cloudinary;
}else{
throw new Error('Expected opts.cloudinary to be a configured cloudinary object.');
}
var paramTemplate = {
remove: null,
upload: null
}
switch (typeof opts.params) {
case 'function': this.getParams = opts.params; break;
case 'undefined': this.getParams = function () {return paramTemplate;};break;
default: throw new TypeError('Expected opts.key to be undefined or function')
}
}
CloudinaryStorage.prototype._handleFile = function _handleFile (req, file, cb) {
var cloudinaryStream = this.cloudinary.uploader.upload_stream(function(result) {
if(!result || result.error){
return cb(result.error.message);
}
cb(null, result)
} , this.getParams().upload);
file.stream.pipe(cloudinaryStream);
};
CloudinaryStorage.prototype._removeFile = function _removeFile (req, file, cb) {
this.cloudinary.v2.uploader.destroy(file.public_id, this.getParams().remove, function (err, result) {
if(err){
return cb(err);
}
return cb(result);
});
}
module.exports = function (opts) {
opts = opts || {};
if(!opts.cloudinary){
throw new Error('Cloudinary object should be passed');
}
return new CloudinaryStorage(opts)
};