This repository has been archived by the owner on Sep 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (61 loc) · 2.03 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const zlib = require('zlib')
const request = require('request')
const omit = require('lodash.omit')
const debug = require('debug')('express-filestack')
// The upload won't work without www in the URL ¯\_(ツ)_/¯
const FILESTACK_API_BASE_URL = 'https://www.filestackapi.com/api'
/**
* Express middleware to pipe multipart/form-data requests to Filestack API.
*
* @param {*} opts
*/
module.exports = function (opts) {
const uploadUrl = opts.uploadUrl || process.env.FILESTACK_UPLOAD_URL
if (!uploadUrl) {
throw new Error('Filestack upload url is not set')
}
if (opts.omitHeaders && !Array.isArray(opts.omitHeaders)) {
throw new Error(`Expected "omitHeaders" to be an Array but received ${typeof opts.omitHeaders}`)
}
if (opts.debug === true) {
debug.enabled = true
}
return function (req, res, next) {
const originalHeaders = req.headers
if (uploadUrl.indexOf(FILESTACK_API_BASE_URL) !== 0) {
throw new Error('Please supply a valid Filestack upload url')
}
req.headers = omit(req.headers, opts.omitHeaders)
const options = {
url: uploadUrl,
headers: {
'Accept-Encoding': 'gzip'
},
encoding: null
}
debug('piping request with the following headers %o', req.headers)
const stream = req.pipe(request.post(options))
stream.on('response', function (resp) {
const chunks = []
debug('gathering response')
resp.on('data', function (chunk) {
chunks.push(chunk)
})
resp.on('end', function () {
const buffer = Buffer.concat(chunks)
debug('decoding gzip response')
zlib.gunzip(buffer, function (err, decoded) {
if (err) {
throw new Error('Cannot decompress gzip response')
}
res.filestack = decoded.toString()
debug('file upload response %s', res.filestack)
// Set headers from the original request
req.headers = originalHeaders
next()
})
})
})
// Do we need to handle the stream error event?
}
}