UNPKG

2.92 kBPlain TextView Raw
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License. See License.txt in the project root for license information.
3
4import { HttpHeaders } from "../httpHeaders";
5import { WebResourceLike } from "../webResource";
6import { ServiceClientCredentials } from "./serviceClientCredentials";
7
8/**
9 * @interface ApiKeyCredentialOptions
10 * Describes the options to be provided while creating an instance of ApiKeyCredentials
11 */
12export interface ApiKeyCredentialOptions {
13 /**
14 * A key value pair of the header parameters that need to be applied to the request.
15 */
16 inHeader?: { [x: string]: any };
17 /**
18 * A key value pair of the query parameters that need to be applied to the request.
19 */
20 inQuery?: { [x: string]: any };
21}
22
23/**
24 * Authenticates to a service using an API key.
25 */
26export class ApiKeyCredentials implements ServiceClientCredentials {
27 /**
28 * A key value pair of the header parameters that need to be applied to the request.
29 */
30 private readonly inHeader?: { [x: string]: any };
31 /**
32 * A key value pair of the query parameters that need to be applied to the request.
33 */
34 private readonly inQuery?: { [x: string]: any };
35
36 /**
37 * @constructor
38 * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
39 */
40 constructor(options: ApiKeyCredentialOptions) {
41 if (!options || (options && !options.inHeader && !options.inQuery)) {
42 throw new Error(
43 `options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`
44 );
45 }
46 this.inHeader = options.inHeader;
47 this.inQuery = options.inQuery;
48 }
49
50 /**
51 * Signs a request with the values provided in the inHeader and inQuery parameter.
52 *
53 * @param {WebResource} webResource The WebResource to be signed.
54 * @returns {Promise<WebResource>} The signed request object.
55 */
56 signRequest(webResource: WebResourceLike): Promise<WebResourceLike> {
57 if (!webResource) {
58 return Promise.reject(
59 new Error(`webResource cannot be null or undefined and must be of type "object".`)
60 );
61 }
62
63 if (this.inHeader) {
64 if (!webResource.headers) {
65 webResource.headers = new HttpHeaders();
66 }
67 for (const headerName in this.inHeader) {
68 webResource.headers.set(headerName, this.inHeader[headerName]);
69 }
70 }
71
72 if (this.inQuery) {
73 if (!webResource.url) {
74 return Promise.reject(new Error(`url cannot be null in the request object.`));
75 }
76 if (webResource.url.indexOf("?") < 0) {
77 webResource.url += "?";
78 }
79 for (const key in this.inQuery) {
80 if (!webResource.url.endsWith("?")) {
81 webResource.url += "&";
82 }
83 webResource.url += `${key}=${this.inQuery[key]}`;
84 }
85 }
86
87 return Promise.resolve(webResource);
88 }
89}