-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpostman.js
94 lines (84 loc) · 3.42 KB
/
postman.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
85
86
87
88
89
90
91
92
93
94
// Receive and handle post data
// (c)copyright 2014 by Gerald Wodni <[email protected]>
"use strict";
const Busboy = require("busboy");
const qs = require("qs");
const _ = require("underscore");
module.exports = function _postman( k ) {
return function postman( req, res, opts, callback ) {
/* if no opts are passed, treat as callback */
if( _.isFunction( opts ) && typeof callback == "undefined" ) {
callback = opts;
opts = {};
}
const contentType = req.get( "Content-Type" );
function addPostman( fields ) {
req.postman = _.extend( req.postman || {}, {
fields: fields,
exists: function( field ) {
/* allow passing of single value or array */
if( ! _.isArray( field ) )
field = [ field ];
return _.every( field, function( f ) {
return f in fields;
});
},
equals: function( field, value ) {
return fields[ field ] == value;
},
fieldsMatch:function( fieldA, fieldB ) {
return fields[ fieldA ] === fields[ fieldB ];
}
} );
/* register postman fetcher */
req.postman = _.extend( req.postman, k.filters.fetch( function( field ) {
return fields[ field ] || "";
}) );
}
if( typeof contentType !== "undefined" && contentType.toLowerCase().indexOf( "multipart/form-data" ) == 0 ) {
let fields = {};
/* connect handlers */
var busboy = new Busboy( _.extend( { headers: req.headers }, opts.busboy ) );
if( !_.has( opts, "onFile" ) )
throw new Error( "multipart/form-data not expected: No file handler installed" );
busboy.on( "file", opts.onFile );
busboy.on( "field", ( name, value ) => {
fields[ name ] = value;
});
busboy.on( "finish", () => {
addPostman( fields );
callback( req, res );
});
busboy.on( "error", (err) => {
console.log( "Postman-Busboy-Error".bold.red, err );
});
req.pipe( busboy );
}
else {
let body = '';
/* handle simple upload */
req.on( 'data', function( data ) {
body += data;
/* beware of multipart filesize */
if( body.length > 2e6 ) {
req.connection.destroy();
console.log( "Postman-body-too-big".bold.red );
}
});
req.on( "end", function() {
switch( contentType ) {
case 'application/json':
req.body = JSON.parse( body );
break;
case 'text/plain':
req.body = body;
break;
/* assume post-data */
default:
addPostman( qs.parse( body, { parseArrays: false } ) );
}
callback( req, res );
});
}
};
};