This repository was archived by the owner on Dec 12, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathRequestExecutor.js
More file actions
119 lines (94 loc) · 3.38 KB
/
RequestExecutor.js
File metadata and controls
119 lines (94 loc) · 3.38 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
'use strict';
var os = require('os');
var request = require('request');
var _ = require('../underscore');
var ResourceError = require('../error/ResourceError');
var authc = require('../authc');
var packageJson = require('../../package.json');
var utils = require('../utils');
var USER_AGENT_VALUE = 'stormpath-sdk-node/' + packageJson.version + ' node/' + process.versions.node + ' ' + os.platform() + '/' + os.release();
/**
*
* @param {object} options
* @constructor
*/
function RequestExecutor(options) {
options = options || {};
this.baseUrl = options.baseUrl || 'https://api.stormpath.com/v1';
this.requestAuthenticator = authc.getAuthenticator(options);
options.headers = options.headers || {};
// Set the user agent appropriately.
options.headers['User-Agent'] = options.userAgent ? options.userAgent + ' ' + USER_AGENT_VALUE : USER_AGENT_VALUE;
options.json = true;
this.options = options;
}
utils.inherits(RequestExecutor, Object);
RequestExecutor.prototype.qualify = function qualify(uri){
if (!uri || _(uri).startsWith('http')) {
return uri;
}
if (_(uri).startsWith('/')) {
return this.baseUrl + uri;
}
return this.baseUrl + '/' + uri;
};
/**
* Executes an HTTP request based on the request object passed in. Request object properties:
* <ul>
* <li>uri: a fully qualified URL. For example, <code>https://api.stormpath.com/v1/tenants/current</code>. REQUIRED.</li>
* <li>method: a String, one of 'GET', 'PUT', 'POST', or 'DELETE' (case-insensitive). OPTIONAL (defaults to GET).</li>
* <li>query: a JSON object to convert to a query string. OPTIONAL.</li>
* <li>body: a JSON object to use as the request body. OPTIONAL.</li>
* </ul>
*
*
* @param req the request to execute
* @param callback the callback to invoke when the request returns
*/
RequestExecutor.prototype.execute = function executeRequest(req, callback) {
var self = this;
if (!req) {
throw new Error('Request argument is required.');
}
if (!req.uri) {
throw new Error('request.uri field is required.');
}
//don't override the defaults: ensure that the options arg is request-specific:
var options = utils.shallowCopy(this.options, {});
if (req.method) { //defaults to GET
options.method = req.method;
}
options.uri = self.qualify(req.uri);
if (req.query) {
options.qs = req.query;
}
if (req.body && req.body.form){
options.form = req.body.form;
}
else if (req.body) {
options.body = req.body;
options.json = true; //all Stormpath resources are JSON
}
this.requestAuthenticator.authenticate(options);
var _s = new Date().getTime();
request(options, function onRequestResult(err, response, body) {
if ( process.env.NODE_DEBUG_SP ) { console.log( 'Fetched stormpath resource:', options.uri, '=> latency(ms):', new Date().getTime() - _s ); }
if (err) {
var wrapper = new Error('Unable to execute http request ' + req + ': ' + err.message);
wrapper.inner = err;
return callback(wrapper, null);
}
if (response.statusCode > 399) {
return callback(new ResourceError(body || {status:response.statusCode}), null);
}
if (response.statusCode === 201){
Object.defineProperty(body, '_isNew', { value: true });
}
if (response.statusCode === 202 && !body){
callback(null, { accepted:true });
}else{
callback(null, body);
}
});
};
module.exports = RequestExecutor;