-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAPIConnectionBuilder.ts
38 lines (31 loc) · 1.51 KB
/
APIConnectionBuilder.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
import { MqttClient } from 'mqtt';
import { IHttpClient } from '../http/IHttpClient';
import { Connection } from '../connection/Connection';
import { IConnection } from '../connection/IConnection';
import { IConnectionBuilder } from './IConnectionBuilder';
import { APIOptions, CloudOptions, BaseCloudOptions } from '../client/ICloudClient';
type AccessResponse = {
access_token: string;
expires_in: string;
token_type: string;
};
function isApiOptions(options: CloudOptions): options is APIOptions {
return !!(options as APIOptions).clientId;
}
export class APIConnectionBuilder implements IConnectionBuilder {
constructor(private client: IHttpClient, private mqttConnect: (string, IClientOptions) => MqttClient) {}
public canBuild(options: CloudOptions): boolean {
return isApiOptions(options);
}
public async build(options: APIOptions & BaseCloudOptions): Promise<IConnection> {
const { apiUrl = 'https://api2.arduino.cc/iot/v1/clients/token' } = options;
const headers = { 'content-type': 'application/x-www-form-urlencoded' };
const body = new URLSearchParams();
body.append('grant_type', 'client_credentials');
body.append('client_id', options.clientId);
body.append('client_secret', options.clientSecret);
body.append('audience', options.audience || 'https://api2.arduino.cc/iot');
const { access_token: accessToken } = await this.client.post<AccessResponse>(apiUrl, body, headers);
return Connection.From(options.host, options.port, accessToken, this.mqttConnect);
}
}