Skip to content

Instantly share code, notes, and snippets.

@thesmart
Created August 16, 2018 17:37
Show Gist options
  • Save thesmart/cffdf49f5eff31a978e9a390bbab1bce to your computer and use it in GitHub Desktop.
Save thesmart/cffdf49f5eff31a978e9a390bbab1bce to your computer and use it in GitHub Desktop.
Dump an http multipart body
import * as when from 'when';
import * as winston from 'winston';
import settings from '../cli';
import * as fs from 'fs';
import * as util from 'util';
/**
* Records a multipart upload for later playback in testing.
* @constructor
*/
var RecorderHandler = function(req, resolve, reject) {
var self = this;
this.req = req;
this.resolve = resolve;
this.reject = reject;
this.destructed = false;
};
/**
* Clean up after an error or on completion
*/
RecorderHandler.prototype.destruct = function() {
this.req.removeAllListeners();
this.destructed = true;
};
/**
* Start handling the request.
*/
RecorderHandler.prototype.start = function() {
var self = this;
var fs = require('fs');
self.req.on('error', function(err) {
winston.error('RECORDING ERROR: %s', err.stack);
self.destruct();
self.reject(err);
});
self.req.on('end', function() {
winston.log('debug', 'RECORDING COMPLETE');
self.destruct();
self.reject({
error: true,
status: 409,
message: 'Upnode in recording mode: ' + path
});
});
var matches = self.req.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i);
var path = settings.root + '/tmp/upnode_' + (matches[1] || matches[2]) + '.log';
var writeStream = fs.createWriteStream(path, {
flags: 'w',
encoding: 'binary',
mode: 0o770
});
winston.log('debug', 'RECORDING STARTING: %s', path);
self.req.pipe(writeStream);
};
/**
* param {http.IncomingMessage} req
* param {http.ServerResponse} res Extended with Figma Middleware
* @returns {Promise}
*/
export default function(req, res) {
return when.promise(function(resolve, reject) {
winston.log('debug', '%s: RECORDER', req.method);
if (req.method != 'POST' || !req.headers['content-type']) {
winston.error('ERROR: invalid method or content type');
return reject(405);
}
// handles the checkpoint multipart parsing
var handler = new RecorderHandler(req, resolve, reject);
handler.start();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment