|
1 | 1 | 'use strict';
|
2 | 2 |
|
3 | 3 | const utils = require('./utils');
|
| 4 | +const {StripeError} = require('./Error'); |
| 5 | + |
| 6 | +class StreamProcessingError extends StripeError {} |
4 | 7 |
|
5 | 8 | // Method for formatting HTTP body for the multipart/form-data specification
|
6 | 9 | // Mostly taken from Fermata.js
|
7 | 10 | // https://github.com/natevw/fermata/blob/5d9732a33d776ce925013a265935facd1626cc88/fermata.js#L315-L343
|
8 |
| -function multipartDataGenerator(method, data, headers) { |
| 11 | +const multipartDataGenerator = (method, data, headers) => { |
9 | 12 | const segno = (
|
10 | 13 | Math.round(Math.random() * 1e16) + Math.round(Math.random() * 1e16)
|
11 | 14 | ).toString();
|
@@ -46,6 +49,46 @@ function multipartDataGenerator(method, data, headers) {
|
46 | 49 | push(`--${segno}--`);
|
47 | 50 |
|
48 | 51 | return buffer;
|
49 |
| -} |
| 52 | +}; |
| 53 | + |
| 54 | +const streamProcessor = (method, data, headers, callback) => { |
| 55 | + const bufferArray = []; |
| 56 | + data.file.data |
| 57 | + .on('data', (line) => { |
| 58 | + bufferArray.push(line); |
| 59 | + }) |
| 60 | + .once('end', () => { |
| 61 | + const bufferData = Object.assign({}, data); |
| 62 | + bufferData.file.data = Buffer.concat(bufferArray); |
| 63 | + const buffer = multipartDataGenerator(method, bufferData, headers); |
| 64 | + callback(null, buffer); |
| 65 | + }) |
| 66 | + .on('error', (err) => { |
| 67 | + callback( |
| 68 | + new StreamProcessingError({ |
| 69 | + message: |
| 70 | + 'An error occurred while attempting to process the file for upload.', |
| 71 | + detail: err, |
| 72 | + }), |
| 73 | + null |
| 74 | + ); |
| 75 | + }); |
| 76 | +}; |
| 77 | + |
| 78 | +const multipartRequestDataProcessor = (method, data, headers, callback) => { |
| 79 | + data = data || {}; |
| 80 | + |
| 81 | + if (method !== 'POST') { |
| 82 | + return callback(null, utils.stringifyRequestData(data)); |
| 83 | + } |
| 84 | + |
| 85 | + const isStream = utils.checkForStream(data); |
| 86 | + if (isStream) { |
| 87 | + return streamProcessor(method, data, headers, callback); |
| 88 | + } |
| 89 | + |
| 90 | + const buffer = multipartDataGenerator(method, data, headers); |
| 91 | + return callback(null, buffer); |
| 92 | +}; |
50 | 93 |
|
51 |
| -module.exports = multipartDataGenerator; |
| 94 | +module.exports.multipartRequestDataProcessor = multipartRequestDataProcessor; |
0 commit comments