forked from microsoftgraph/msgraph-sdk-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPClient.ts
More file actions
88 lines (81 loc) · 2.38 KB
/
HTTPClient.ts
File metadata and controls
88 lines (81 loc) · 2.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
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module HTTPClient
*/
import { Context } from "./IContext";
import { Middleware } from "./middleware/IMiddleware";
/**
* @class
* Class representing HTTPClient
*/
export class HTTPClient {
/**
* @private
* A member holding first middleware of the middleware chain
*/
private middleware: Middleware;
/**
* @public
* @constructor
* Creates an instance of a HTTPClient
* @param {Middleware} middleware - The first middleware of the middleware chain
*/
public constructor(middleware: Middleware) {
this.middleware = middleware;
}
/**
* @public
* To get an array of Middleware, used in middleware chain
* @returns An array of middlewares
*/
public getMiddlewareArray(): Middleware[] {
const middlewareArray: Middleware[] = [];
let currentMiddleware = this.middleware;
while (currentMiddleware) {
middlewareArray.push(currentMiddleware);
if (typeof currentMiddleware.getNext !== "undefined") {
currentMiddleware = currentMiddleware.getNext();
} else {
break;
}
}
return middlewareArray;
}
/**
* @public
* To set the middleware chain
* @param {Middleware[]} middlewareArray - The array containing the middlewares
*/
public setMiddlewareArray(middlewareArray: Middleware[]) {
for (let num = 0; num < middlewareArray.length - 1; num += 1) {
middlewareArray[num].setNext(middlewareArray[num + 1]);
}
this.middleware = middlewareArray[0];
}
/**
* @public
* @async
* To send the request through the middleware chain
* @param {Context} context - The context of a request
* @returns A promise that resolves to the Context
*/
public async sendRequest(context: Context): Promise<Context> {
try {
if (typeof context.request === "string" && context.options === undefined) {
const error = new Error();
error.name = "InvalidRequestOptions";
error.message = "Unable to execute the middleware, Please provide valid options for a request";
throw error;
}
await this.middleware.execute(context);
return context;
} catch (error) {
throw error;
}
}
}