1 |
|
2 |
|
3 |
|
4 | import { HttpHeaders } from "../httpHeaders";
|
5 | import { WebResourceLike } from "../webResource";
|
6 | import { ServiceClientCredentials } from "./serviceClientCredentials";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | export interface ApiKeyCredentialOptions {
|
13 | |
14 |
|
15 |
|
16 | inHeader?: { [x: string]: any };
|
17 | |
18 |
|
19 |
|
20 | inQuery?: { [x: string]: any };
|
21 | }
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | export class ApiKeyCredentials implements ServiceClientCredentials {
|
27 | |
28 |
|
29 |
|
30 | private readonly inHeader?: { [x: string]: any };
|
31 | |
32 |
|
33 |
|
34 | private readonly inQuery?: { [x: string]: any };
|
35 |
|
36 | |
37 |
|
38 |
|
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 |
|
52 |
|
53 |
|
54 |
|
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 | }
|