-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
70 lines (57 loc) · 1.68 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var Promise = require('bluebird')
var FTP = require('ftp')
var path = require('path')
var defaults = require('lodash.defaults')
var random = Promise.promisify(require('crypto').randomBytes)
function getDestination (req, file, opts, cb) {
random(16).then(function(raw) {
cb(null, path.join(opts.basepath, raw.toString('hex') + path.extname(file.originalname)))
}, cb)
}
function FTPStorage (opts) {
this.opts = defaults(opts, {
basepath: '',
destination: getDestination
})
if (this.opts.connection) {
this.ftp = this.opts.connection
this.ready = Promise.resolve()
} else {
this.ftp = new FTP()
this.ready = new Promise(function (resolve, reject) {
this.ftp.on('ready', resolve)
}.bind(this))
this.ftp.connect(this.opts.ftp)
}
}
FTPStorage.prototype._handleFile = function _handleFile (req, file, cb) {
var instance = this
function handleFile (stream) {
instance.opts.destination(req, file, instance.opts, function (err, destination) {
if (err) return cb(err)
instance.ftp.put(stream, destination, function (err) {
if (err) return cb(err)
cb(null, {
path: destination
})
})
})
}
instance.ready.then(function () {
if (instance.opts.transformFile) {
instance.opts.transformFile(req, file, function (err, stream) {
if (err) return cb(err)
file.transformedStream = stream
handleFile(file.transformedStream)
})
} else {
handleFile(file.stream)
}
})
}
FTPStorage.prototype._removeFile = function _removeFile(req, file, cb) {
this.ready.then(function () {
this.ftp.delete(file.path, cb)
}.bind(this))
}
module.exports = FTPStorage