-
Notifications
You must be signed in to change notification settings - Fork 117
/
RestClient.ts
265 lines (223 loc) · 9.96 KB
/
RestClient.ts
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import httpm = require('./HttpClient');
import ifm = require("./Interfaces");
import util = require("./Util");
export interface IRestResponse<T> {
statusCode: number,
result: T | null,
headers: Object
}
export interface IRequestOptions {
// defaults to application/json
// common versioning is application/json;version=2.1
acceptHeader?: string,
// since accept is defaulted, set additional headers if needed
additionalHeaders?: ifm.IHeaders,
responseProcessor?: Function,
//Dates aren't automatically deserialized by JSON, this adds a date reviver to ensure they aren't just left as strings
deserializeDates?: boolean
}
export class RestClient {
client: httpm.HttpClient;
versionParam: string;
/**
* Creates an instance of the RestClient
* @constructor
* @param {string} userAgent - userAgent for requests
* @param {string} baseUrl - (Optional) If not specified, use full urls per request. If supplied and a function passes a relative url, it will be appended to this
* @param {ifm.IRequestHandler[]} handlers - handlers are typically auth handlers (basic, bearer, ntlm supplied)
* @param {ifm.IRequestOptions} requestOptions - options for each http requests (http proxy setting, socket timeout)
*/
constructor(userAgent: string,
baseUrl?: string,
handlers?: ifm.IRequestHandler[],
requestOptions?: ifm.IRequestOptions) {
this.client = new httpm.HttpClient(userAgent, handlers, requestOptions);
if (baseUrl) {
this._baseUrl = baseUrl;
}
}
private _baseUrl: string;
/**
* Gets a resource from an endpoint
* Be aware that not found returns a null. Other error conditions reject the promise
* @param {string} requestUrl - fully qualified or relative url
* @param {IRequestOptions} requestOptions - (optional) requestOptions object
*/
public async options<T>(requestUrl: string,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(requestUrl, this._baseUrl);
let res: httpm.HttpClientResponse = await this.client.options(url,
this._headersFromOptions(options));
return this._processResponse<T>(res, options);
}
/**
* Gets a resource from an endpoint
* Be aware that not found returns a null. Other error conditions reject the promise
* @param {string} resource - fully qualified url or relative path
* @param {IRequestOptions} requestOptions - (optional) requestOptions object
*/
public async get<T>(resource: string,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(resource, this._baseUrl);
let res: httpm.HttpClientResponse = await this.client.get(url,
this._headersFromOptions(options));
return this._processResponse<T>(res, options);
}
/**
* Deletes a resource from an endpoint
* Be aware that not found returns a null. Other error conditions reject the promise
* @param {string} resource - fully qualified or relative url
* @param {IRequestOptions} requestOptions - (optional) requestOptions object
*/
public async del<T>(resource: string,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(resource, this._baseUrl);
let res: httpm.HttpClientResponse = await this.client.del(url,
this._headersFromOptions(options));
return this._processResponse<T>(res, options);
}
/**
* Creates resource(s) from an endpoint
* T type of object returned.
* Be aware that not found returns a null. Other error conditions reject the promise
* @param {string} resource - fully qualified or relative url
* @param {IRequestOptions} requestOptions - (optional) requestOptions object
*/
public async create<T>(resource: string,
resources: any,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(resource, this._baseUrl);
let headers: ifm.IHeaders = this._headersFromOptions(options, true);
let data: string = JSON.stringify(resources, null, 2);
let res: httpm.HttpClientResponse = await this.client.post(url, data, headers);
return this._processResponse<T>(res, options);
}
/**
* Updates resource(s) from an endpoint
* T type of object returned.
* Be aware that not found returns a null. Other error conditions reject the promise
* @param {string} resource - fully qualified or relative url
* @param {IRequestOptions} requestOptions - (optional) requestOptions object
*/
public async update<T>(resource: string,
resources: any,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(resource, this._baseUrl);
let headers: ifm.IHeaders = this._headersFromOptions(options, true);
let data: string = JSON.stringify(resources, null, 2);
let res: httpm.HttpClientResponse = await this.client.patch(url, data, headers);
return this._processResponse<T>(res, options);
}
/**
* Replaces resource(s) from an endpoint
* T type of object returned.
* Be aware that not found returns a null. Other error conditions reject the promise
* @param {string} resource - fully qualified or relative url
* @param {IRequestOptions} requestOptions - (optional) requestOptions object
*/
public async replace<T>(resource: string,
resources: any,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(resource, this._baseUrl);
let headers: ifm.IHeaders = this._headersFromOptions(options, true);
let data: string = JSON.stringify(resources, null, 2);
let res: httpm.HttpClientResponse = await this.client.put(url, data, headers);
return this._processResponse<T>(res, options);
}
public async uploadStream<T>(verb: string,
requestUrl: string,
stream: NodeJS.ReadableStream,
options?: IRequestOptions): Promise<IRestResponse<T>> {
let url: string = util.getUrl(requestUrl, this._baseUrl);
let headers: ifm.IHeaders = this._headersFromOptions(options, true);
let res: httpm.HttpClientResponse = await this.client.sendStream(verb, url, stream, headers);
return this._processResponse<T>(res, options);
}
private _headersFromOptions(options: IRequestOptions, contentType?: boolean): ifm.IHeaders {
options = options || {};
let headers: ifm.IHeaders = options.additionalHeaders || {};
headers["Accept"] = options.acceptHeader || "application/json";
if (contentType) {
let found: boolean = false;
for (let header in headers) {
if (header.toLowerCase() == "content-type") {
found = true;
}
}
if (!found) {
headers["Content-Type"] = 'application/json; charset=utf-8';
}
}
return headers;
}
private static dateTimeDeserializer(key: any, value: any): any {
if (typeof value === 'string'){
let a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
private async _processResponse<T>(res: httpm.HttpClientResponse, options: IRequestOptions): Promise<IRestResponse<T>> {
return new Promise<IRestResponse<T>>(async (resolve, reject) => {
const statusCode: number = res.message.statusCode;
const response: IRestResponse<T> = {
statusCode: statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode == httpm.HttpCodes.NotFound) {
resolve(response);
}
let obj: any;
let contents: string;
// get the result from the body
try {
contents = await res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, RestClient.dateTimeDeserializer);
} else {
obj = JSON.parse(contents);
}
if (options && options.responseProcessor) {
response.result = options.responseProcessor(obj);
}
else {
response.result = obj;
}
}
response.headers = res.message.headers;
}
catch (err) {
// Invalid resource (contents not json); leaving result obj null
}
// note that 3xx redirects are handled by the http layer.
if (statusCode > 299) {
let msg: string;
// if exception/error in body, attempt to get better error
if (obj && obj.message) {
msg = obj.message;
} else if (contents && contents.length > 0) {
// it may be the case that the exception is in the body message as string
msg = contents;
} else {
msg = "Failed request: (" + statusCode + ")";
}
let err: Error = new Error(msg);
// attach statusCode and body obj (if available) to the error object
err['statusCode'] = statusCode;
if (response.result) {
err['result'] = response.result;
}
reject(err);
} else {
resolve(response);
}
});
}
}