UNPKG

2.86 kBPlain TextView Raw
1/**
2 * -------------------------------------------------------------------------------------------
3 * Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
4 * See License in the project root for license information.
5 * -------------------------------------------------------------------------------------------
6 */
7
8/**
9 * @module HTTPClient
10 */
11
12import { Context } from "./IContext";
13import { Middleware } from "./middleware/IMiddleware";
14
15/**
16 * @class
17 * Class representing HTTPClient
18 */
19export class HTTPClient {
20 /**
21 * @private
22 * A member holding first middleware of the middleware chain
23 */
24 private middleware: Middleware;
25
26 /**
27 * @public
28 * @constructor
29 * Creates an instance of a HTTPClient
30 * @param {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
31 */
32 public constructor(...middleware: Middleware[]) {
33 if (!middleware || !middleware.length) {
34 const error = new Error();
35 error.name = "InvalidMiddlewareChain";
36 error.message = "Please provide a default middleware chain or custom middleware chain";
37 throw error;
38 }
39 this.setMiddleware(...middleware);
40 }
41
42 /**
43 * @private
44 * Processes the middleware parameter passed to set this.middleware property
45 * The calling function should validate if middleware is not undefined or not empty.
46 * @param {...Middleware} middleware - The middleware passed
47 * @returns Nothing
48 */
49 private setMiddleware(...middleware: Middleware[]): void {
50 if (middleware.length > 1) {
51 this.parseMiddleWareArray(middleware);
52 } else {
53 this.middleware = middleware[0];
54 }
55 }
56
57 /**
58 * @private
59 * Processes the middleware array to construct the chain
60 * and sets this.middleware property to the first middleware handler of the array
61 * The calling function should validate if middleware is not undefined or not empty
62 * @param {Middleware[]} middlewareArray - The array of middleware handlers
63 * @returns Nothing
64 */
65 private parseMiddleWareArray(middlewareArray: Middleware[]) {
66 middlewareArray.forEach((element, index) => {
67 if (index < middlewareArray.length - 1) {
68 element.setNext(middlewareArray[index + 1]);
69 }
70 });
71 this.middleware = middlewareArray[0];
72 }
73
74 /**
75 * @public
76 * @async
77 * To send the request through the middleware chain
78 * @param {Context} context - The context of a request
79 * @returns A promise that resolves to the Context
80 */
81 public async sendRequest(context: Context): Promise<Context> {
82 if (typeof context.request === "string" && context.options === undefined) {
83 const error = new Error();
84 error.name = "InvalidRequestOptions";
85 error.message = "Unable to execute the middleware, Please provide valid options for a request";
86 throw error;
87 }
88 await this.middleware.execute(context);
89 return context;
90 }
91}