forked from ddikman/QC.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqcApi.js
More file actions
212 lines (153 loc) · 5.07 KB
/
Copy pathqcApi.js
File metadata and controls
212 lines (153 loc) · 5.07 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
var Promise = require('promise');
var cookies = require('cookie');
var util = require('util');
var Client = new require('node-rest-client').Client;
InvalidAuthenticationException = function(msg){
this.message = msg;
this.name = "InvalidAuthenticationException";
};
FailedRequestException = function(msg, statusCode, response, url){
this.message = msg;
this.response = response;
this.statusCode = statusCode;
this.url = url;
this.name = "FailedRequestException";
};
var qcApi = function(){
this.isAuthenticated = false;
};
qcApi.prototype.getClient = function(args){
return new Client(args);
};
qcApi.prototype.trimSlash = function(url){
if(url)
{
if(typeof(url) != 'string')
throw 'Url is not string: ' + url;
if(url.length > 0 && url[url.length - 1] == '/')
url = url.substr(0, url.length - 1);
if(url.length > 0 && url[0] == '/')
url = url.substr(1, url.length);
}
return url;
};
qcApi.prototype.prependSlash = function(url){
return url[0] == '/' ? url : "/" + url;
}
qcApi.prototype.startSession = function(){
var promise = new Promise(function(resolve, reject){
this.client.post(this.rootUrl + "/rest/site-session", { headers: { cookie : this.authCookie } }, function(data, res){
if(res.statusCode != 201)
{
reject("Session start failed, status code " + res.statusCode);
return;
}
this.authCookie += ";" + res.headers['set-cookie'].join(';');
resolve();
}.bind(this));
}.bind(this));
return promise;
}
qcApi.prototype.login = function(connInfo){
var promise = new Promise(function(resolve, reject){
this.rootUrl = this.trimSlash(connInfo.server);
this.connInfo = connInfo;
this.client = this.getClient({user: connInfo.user, password: connInfo.password});
this.domain = connInfo.domain;
this.project = connInfo.project;
this.client.get(this.rootUrl + "/authentication-point/authenticate", function handleAuthResponse(data, res){
if(res.statusCode == 200)
{
this.isAuthenticated = true;
this.authCookie = res.headers['set-cookie'].join(';');
this.startSession().then(resolve, reject);
}
else if(res.statusCode == 401)
{
this.isAuthenticated = false;
reject(new InvalidAuthenticationException(util.format("Failed to authenticate '%s' against %s, please verify username and password are correct", connInfo.user, this.rootUrl)));
}
else
{
this.isAuthenticated = false;
var error = new InvalidAuthenticationException(util.format("Failed to authenticate '%s' against %s: status code %s", connInfo.user, this.rootUrl, res.statusCode));
error.response = data.toString('utf8');
reject(error);
}
}.bind(this));
}.bind(this));
return promise;
};
qcApi.prototype.verifyAuthenticated = function(){
if(!this.isAuthenticated)
throw new InvalidAuthenticationException("Not yet logged in, please call login to authenticate.");
}
/**
* If the REST call response is an entity, some processing is performed on the resulting javascript object, such as putting each field as a property
* on the object instead of an object in the entities property list
* @param {obj} Should be a javascript object returned from the node-rest-client, parsed from a REST call xml or json response
*/
qcApi.prototype.convertResult = function(obj){
if(obj.Entities == undefined)
return obj;
var result = [];
result.totalResults = parseInt(obj.Entities['$'].TotalResults);
if(result.totalResults == 0)
return result;
obj.Entities.Entity.forEach(function(entity){
var convertedEntity = {
type: entity['$'].Type
};
entity.Fields[0].Field.forEach(function(field){
var name = field['$'].Name;
var value = field.Value ? field.Value[0] : null;
convertedEntity[name] = value;
});
result.push(convertedEntity);
});
return result;
};
qcApi.prototype.buildUrl = function(url, options){
targetUrl = this.rootUrl + "/rest";
if(this.domain)
{
targetUrl += "/domains/" + this.domain;
if(this.project)
targetUrl += "/projects/" + this.project;
}
targetUrl += this.prependSlash(url);
if(options)
{
if(typeof(options) != 'object')
throw 'Expected parameter options to be an object but got ' + typeof(options);
var queryString = [];
if(options.pageSize)
queryString.push('page-size=' + options.pageSize);
if(options.fields && options.fields.length != undefined)
queryString.push('fields=' + options.fields.join(','));
if(queryString.length > 0)
{
var appendCharacter = url.indexOf('?') >= 0 ? '&' : '?';
targetUrl = targetUrl + appendCharacter + queryString.join('&');
}
}
return targetUrl;
};
qcApi.prototype.get = function(url, options) {
var promise = new Promise(function(resolve, reject){
this.verifyAuthenticated();
url = this.buildUrl(url, options);
this.client.get(url, { headers: { cookie: this.authCookie } }, function handleGetResponse(data, res){
if(res.statusCode != 200)
reject(new FailedRequestException("Failed to process url", res.statusCode, data.toString('utf8'), url));
else
resolve(this.convertResult(data));
}.bind(this));
}.bind(this));
return promise;
};
module.exports = {
create: function(){
return new qcApi();
}
};