/
apiKeyCredentials.ts
87 lines (79 loc) · 2.68 KB
/
apiKeyCredentials.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { HttpHeaders } from "../httpHeaders";
import { WebResourceLike } from "../webResource";
import { ServiceClientCredentials } from "./serviceClientCredentials";
/**
* Describes the options to be provided while creating an instance of ApiKeyCredentials
*/
export interface ApiKeyCredentialOptions {
/**
* A key value pair of the header parameters that need to be applied to the request.
*/
inHeader?: { [x: string]: any };
/**
* A key value pair of the query parameters that need to be applied to the request.
*/
inQuery?: { [x: string]: any };
}
/**
* Authenticates to a service using an API key.
*/
export class ApiKeyCredentials implements ServiceClientCredentials {
/**
* A key value pair of the header parameters that need to be applied to the request.
*/
private readonly inHeader?: { [x: string]: any };
/**
* A key value pair of the query parameters that need to be applied to the request.
*/
private readonly inQuery?: { [x: string]: any };
/**
* @param options - Specifies the options to be provided for auth. Either header or query needs to be provided.
*/
constructor(options: ApiKeyCredentialOptions) {
if (!options || (options && !options.inHeader && !options.inQuery)) {
throw new Error(
`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`
);
}
this.inHeader = options.inHeader;
this.inQuery = options.inQuery;
}
/**
* Signs a request with the values provided in the inHeader and inQuery parameter.
*
* @param webResource - The WebResourceLike to be signed.
* @returns The signed request object.
*/
signRequest(webResource: WebResourceLike): Promise<WebResourceLike> {
if (!webResource) {
return Promise.reject(
new Error(`webResource cannot be null or undefined and must be of type "object".`)
);
}
if (this.inHeader) {
if (!webResource.headers) {
webResource.headers = new HttpHeaders();
}
for (const headerName in this.inHeader) {
webResource.headers.set(headerName, this.inHeader[headerName]);
}
}
if (this.inQuery) {
if (!webResource.url) {
return Promise.reject(new Error(`url cannot be null in the request object.`));
}
if (webResource.url.indexOf("?") < 0) {
webResource.url += "?";
}
for (const key in this.inQuery) {
if (!webResource.url.endsWith("?")) {
webResource.url += "&";
}
webResource.url += `${key}=${this.inQuery[key]}`;
}
}
return Promise.resolve(webResource);
}
}