-
Notifications
You must be signed in to change notification settings - Fork 776
/
Copy pathFiles.js
80 lines (71 loc) · 2.1 KB
/
Files.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
'use strict';
const utils = require('../utils');
const multipartDataGenerator = require('../MultipartDataGenerator');
const Error = require('../Error');
const StripeResource = require('../StripeResource');
const stripeMethod = StripeResource.method;
module.exports = StripeResource.extend({
path: 'files',
includeBasic: ['list', 'retrieve'],
requestDataProcessor(method, data, headers, callback) {
data = data || {};
if (method === 'POST') {
return getProcessorForSourceType(data);
} else {
return callback(null, utils.stringifyRequestData(data));
}
function getProcessorForSourceType(data) {
const isStream = utils.checkForStream(data);
if (isStream) {
return streamProcessor(multipartDataGenerator);
} else {
const buffer = multipartDataGenerator(method, data, headers);
return callback(null, buffer);
}
}
function streamProcessor(fn) {
const bufferArray = [];
data.file.data
.on('data', (line) => {
bufferArray.push(line);
})
.on('end', () => {
const bufferData = Object.assign({}, data);
bufferData.file.data = Buffer.concat(bufferArray);
const buffer = fn(method, bufferData, headers);
callback(null, buffer);
})
.on('error', (err) => {
const errorHandler = streamError(callback);
errorHandler(err);
});
}
function streamError(callback) {
const StreamProcessingError = Error.extend({
type: 'StreamProcessingError',
populate(raw) {
this.type = this.type;
this.message = raw.message;
this.detail = raw.detail;
},
});
return (error) => {
callback(
new StreamProcessingError({
message:
'An error occurred while attempting to process the file for upload.',
detail: error,
}),
null
);
};
}
},
create: stripeMethod({
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
host: 'files.stripe.com',
}),
});