forked from mock-server/mockserver-client-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendRequest.js
87 lines (73 loc) · 2.64 KB
/
sendRequest.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
/*
* mockserver
* http://mock-server.com
*
* Copyright (c) 2014 James Bloom
* Licensed under the Apache License, Version 2.0
*/
(function () {
"use strict";
if (module && require) {
var Q = require('q');
var http = require('http');
var defer = function () {
var promise = (global.protractor ? protractor.promise : Q);
var deferred = promise.defer();
if (deferred.fulfill && !deferred.resolve) {
deferred.resolve = deferred.fulfill;
}
return deferred;
};
var sendRequest = function (host, port, path, jsonBody, resolveCallback) {
var deferred = defer();
var body = (typeof jsonBody === "string" ? jsonBody : JSON.stringify(jsonBody || ""));
var options = {
method: 'PUT',
host: host,
path: path,
port: port,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
};
var req = http.request(options);
req.once('response', function (response) {
var data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
if (resolveCallback) {
deferred.resolve(resolveCallback(data));
} else {
if (response.statusCode >= 400 && response.statusCode < 600) {
if (response.statusCode === 404) {
deferred.reject("404 Not Found");
} else {
deferred.reject(data);
}
} else {
deferred.resolve({
statusCode: response.statusCode,
body: data
});
}
}
});
});
req.once('error', function (error) {
if (error.code && error.code === "ECONNREFUSED") {
deferred.reject("Can't connect to MockServer running on host: \"" + host + "\" and port: \"" + port + "\"");
} else {
deferred.reject(JSON.stringify(error));
}
});
req.write(body);
req.end();
return deferred.promise;
};
module.exports = {
sendRequest: sendRequest
};
}
})();