Skip to content

Commit 509b194

Browse files
committedJun 18, 2020
Lint
1 parent 2432767 commit 509b194

16 files changed

+428
-233
lines changed
 

‎.eslintrc.js

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ module.exports = {
55
ignorePatterns: ['node_modules/*', 'lib/*', 'es/*'],
66
parser: '@typescript-eslint/parser',
77
extends: [
8-
'plugin:react/recommended',
98
'plugin:@typescript-eslint/recommended',
109
'prettier/@typescript-eslint',
1110
'plugin:prettier/recommended',
@@ -23,14 +22,7 @@ module.exports = {
2322
'@typescript-eslint/no-empty-interface': 'warn',
2423
'@typescript-eslint/no-empty-function': 'warn',
2524
'@typescript-eslint/no-namespace': 'warn',
26-
'react/display-name': 'warn',
27-
'react/prop-types': 'warn',
2825
'prefer-rest-params': 'warn',
2926
'no-else-return': 'error',
3027
},
31-
settings: {
32-
react: {
33-
version: 'detect',
34-
},
35-
},
3628
};

‎.prettierrc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"printWidth": 120,
3+
"singleQuote": true,
4+
"trailingComma": "es5"
5+
}

‎package-lock.json

Lines changed: 217 additions & 89 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,19 @@
3030
"@types/jest": "^26.0.0",
3131
"@types/jws": "^3.2.2",
3232
"@types/mqtt": "^2.5.0",
33+
"@types/node": "^14.0.13",
3334
"@types/node-fetch": "^2.5.7",
3435
"@types/react": "^16.9.13",
3536
"@types/react-dom": "^16.9.4",
3637
"@types/sinon": "^7.5.1",
3738
"@types/whatwg-fetch": "0.0.33",
38-
"eslint": "^7.2.0",
39+
"@typescript-eslint/eslint-plugin": "^2.25.0",
40+
"@typescript-eslint/parser": "^2.25.0",
41+
"eslint": "^6.8.0",
42+
"eslint-config-prettier": "^6.10.1",
43+
"eslint-plugin-prettier": "^3.1.2",
3944
"jest": "^26.0.1",
45+
"prettier": "^2.0.5",
4046
"rimraf": "^3.0.2",
4147
"rollup": "^2.3.3",
4248
"rollup-plugin-peer-deps-external": "^2.2.2",
@@ -47,8 +53,8 @@
4753
},
4854
"scripts": {
4955
"test": "npm run build && jest --config ./jest.config.js",
50-
"lint": "eslint src",
51-
"lint-fix": "eslint --fix src --ext .js",
56+
"lint": "eslint src/**/*.ts",
57+
"lint:fix": "eslint src/**/*.ts --fix",
5258
"clean": "rimraf lib es",
5359
"build:es": "rollup -c",
5460
"build:lib": "rollup -c ./rollup.config.lib.js",

‎src/@arduino/cbor-js.d.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
+---------------+-------+------------+------------+------------+
2424
*/
2525

26-
2726
declare module '@arduino/cbor-js' {
2827
export function encode(value: SenML[], numericKeys?: boolean): ArrayBuffer;
2928
export function decode(data: ArrayBuffer, tagger?: (value: SenML) => SenML, simpleValue?: SenML): SenML[];
@@ -45,5 +44,5 @@ declare module '@arduino/cbor-js' {
4544
t?: number;
4645
ut?: number;
4746
[key: string]: any;
48-
}
49-
}
47+
};
48+
}

‎src/builder/APIConnectionBuilder.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,37 @@
11
import { IHttpClient } from '../http/IHttpClient';
2-
import { Connection } from "../connection/Connection";
3-
import { IConnection } from "../connection/IConnection";
2+
import { Connection } from '../connection/Connection';
3+
import { IConnection } from '../connection/IConnection';
44
import { IConnectionBuilder } from './IConnectionBuilder';
5-
import { APIOptions, CloudOptions, BaseCloudOptions } from "../client/ICloudClient";
5+
import { APIOptions, CloudOptions, BaseCloudOptions } from '../client/ICloudClient';
66

77
type AccessResponse = {
8-
"access_token": string;
9-
"expires_in": string;
10-
"token_type": string;
11-
}
8+
access_token: string;
9+
expires_in: string;
10+
token_type: string;
11+
};
1212

1313
export class APIConnectionBuilder implements IConnectionBuilder {
14-
constructor(private client: IHttpClient) { }
14+
constructor(private client: IHttpClient) {}
1515

1616
public canBuild(options: CloudOptions): boolean {
1717
return isApiOptions(options);
1818
}
1919

2020
public async build(options: APIOptions & BaseCloudOptions): Promise<IConnection> {
21-
const { apiUrl = "https://api2.arduino.cc/iot/v1/clients/token" } = options;
21+
const { apiUrl = 'https://api2.arduino.cc/iot/v1/clients/token' } = options;
2222
const headers = { 'content-type': 'application/x-www-form-urlencoded' };
2323

2424
const body = new URLSearchParams();
25-
body.append("grant_type", 'client_credentials');
26-
body.append("client_id", options.clientId);
27-
body.append("client_secret", options.clientSecret);
28-
body.append("audience", options.audience || 'https://api2.arduino.cc/iot');
25+
body.append('grant_type', 'client_credentials');
26+
body.append('client_id', options.clientId);
27+
body.append('client_secret', options.clientSecret);
28+
body.append('audience', options.audience || 'https://api2.arduino.cc/iot');
2929

3030
const { access_token } = await this.client.post<AccessResponse>(apiUrl, body, headers);
31-
return Connection.From(options.host, options.port, access_token)
31+
return Connection.From(options.host, options.port, access_token);
3232
}
3333
}
3434

3535
function isApiOptions(options: CloudOptions): options is APIOptions {
3636
return !!(options as APIOptions).clientId;
37-
}
37+
}

‎src/builder/IConnectionBuilder.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { IConnection } from "../connection/IConnection";
2-
import { CloudOptions } from "../client/ICloudClient";
1+
import { IConnection } from '../connection/IConnection';
2+
import { CloudOptions } from '../client/ICloudClient';
33

44
export interface IConnectionBuilder {
55
canBuild(options: CloudOptions): boolean;
66
build(options: CloudOptions): Promise<IConnection>;
7-
}
7+
}

‎src/builder/TokenConnectionBuilder.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { Connection } from "../connection/Connection";
2-
import { IConnection } from "../connection/IConnection";
1+
import { Connection } from '../connection/Connection';
2+
import { IConnection } from '../connection/IConnection';
33
import { IConnectionBuilder } from './IConnectionBuilder';
4-
import { BrowserOptions, CloudOptions, BaseCloudOptions } from "../client/ICloudClient";
4+
import { BrowserOptions, CloudOptions, BaseCloudOptions } from '../client/ICloudClient';
55

66
export class TokenConnectionBuilder implements IConnectionBuilder {
77
canBuild(options: CloudOptions): boolean {

‎src/client/CloudClient.ts

Lines changed: 40 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import { filter } from "rxjs/operators";
2-
import { Subscription, Subject, Observable } from "rxjs";
1+
import { filter } from 'rxjs/operators';
2+
import { Subscription, Subject, Observable } from 'rxjs';
33

4-
import SenML from "../senML";
5-
import Utils from "../utils";
4+
import SenML from '../senML';
5+
import Utils from '../utils';
66
import { IConnectionBuilder } from '../builder/IConnectionBuilder';
7-
import { IConnection, CloudMessage } from "../connection/IConnection";
8-
import { ICloudClient, CloudOptions, OnMessageCallback, CloudMessageValue } from "./ICloudClient";
7+
import { IConnection, CloudMessage } from '../connection/IConnection';
8+
import { ICloudClient, CloudOptions, OnMessageCallback, CloudMessageValue } from './ICloudClient';
99

1010
const NOOP = () => null;
1111
export class CloudClient implements ICloudClient {
@@ -30,15 +30,15 @@ export class CloudClient implements ICloudClient {
3030
return client;
3131
}
3232

33-
constructor(private builders: IConnectionBuilder[] = []) { }
33+
constructor(private builders: IConnectionBuilder[] = []) {}
3434

3535
public async connect(options: CloudOptions): Promise<IConnection> {
3636
this.options = { ...this.options, ...options };
37-
const builder = this.builders.find(b => b.canBuild(this.options));
37+
const builder = this.builders.find((b) => b.canBuild(this.options));
3838

3939
if (!builder) throw new Error('connection failed: options not valid');
4040

41-
const connection = await builder.build(this.options)
41+
const connection = await builder.build(this.options);
4242
return this.init(connection);
4343
}
4444

@@ -69,7 +69,7 @@ export class CloudClient implements ICloudClient {
6969

7070
this.connection = null;
7171
Object.values(this.subscriptions).forEach((subs, topic) => {
72-
subs.forEach(sub => sub.unsubscribe())
72+
subs.forEach((sub) => sub.unsubscribe());
7373
delete this.callbacks[topic];
7474
delete this.subscriptions[topic];
7575
});
@@ -92,14 +92,14 @@ export class CloudClient implements ICloudClient {
9292

9393
await this.connect({ ...this.options, token: newToken });
9494

95-
Object.keys(this.subscriptions).forEach(topic => {
96-
this.subscriptions[topic].forEach(sub => sub.unsubscribe());
95+
Object.keys(this.subscriptions).forEach((topic) => {
96+
this.subscriptions[topic].forEach((sub) => sub.unsubscribe());
9797
delete this.subscriptions[topic];
9898

9999
const callbacks = [...this.callbacks[topic]];
100100
delete this.callbacks[topic];
101-
callbacks.forEach(cb => this.subscribe(topic, cb));
102-
})
101+
callbacks.forEach((cb) => this.subscribe(topic, cb));
102+
});
103103

104104
const { onConnected = NOOP } = this.options;
105105
onConnected();
@@ -122,7 +122,10 @@ export class CloudClient implements ICloudClient {
122122
if (!this.connection) return reject(new Error('send message failed: no connection found'));
123123

124124
const body = Utils.isString(message) ? Buffer.from(message, 'utf8') : message;
125-
this.connection.publish(topic, Utils.toBuffer(body), { qos: 1, retain: false });
125+
this.connection.publish(topic, Utils.toBuffer(body), {
126+
qos: 1,
127+
retain: false,
128+
});
126129
return resolve();
127130
});
128131
}
@@ -139,13 +142,25 @@ export class CloudClient implements ICloudClient {
139142
return this.unsubscribe(`/a/d/${deviceId}/s/o`);
140143
}
141144

142-
public async sendProperty<T extends CloudMessageValue>(thingId: string, name: string, value: T, timestamp: number = new Date().getTime()): Promise<void> {
145+
public async sendProperty<T extends CloudMessageValue>(
146+
thingId: string,
147+
name: string,
148+
value: T,
149+
timestamp: number = new Date().getTime()
150+
): Promise<void> {
143151
const topic = `/a/t/${thingId}/e/i`;
144152
const values = SenML.parse(name, value, timestamp, this.options.useCloudProtocolV2, null);
145-
return this.sendMessage(topic, SenML.CBOR.encode(Utils.isArray(values) ? values : [values], this.options.useCloudProtocolV2));
153+
return this.sendMessage(
154+
topic,
155+
SenML.CBOR.encode(Utils.isArray(values) ? values : [values], this.options.useCloudProtocolV2)
156+
);
146157
}
147158

148-
public async onPropertyValue<T extends CloudMessageValue>(thingId: string, name: string, cb: OnMessageCallback<T>): Promise<void> {
159+
public async onPropertyValue<T extends CloudMessageValue>(
160+
thingId: string,
161+
name: string,
162+
cb: OnMessageCallback<T>
163+
): Promise<void> {
149164
if (!name) throw new Error('Invalid property name');
150165
if (typeof cb !== 'function') throw new Error('Invalid callback');
151166

@@ -157,8 +172,9 @@ export class CloudClient implements ICloudClient {
157172
this.callbacks[topic].push(cb);
158173
this.subscriptions[topic].push(
159174
this.messagesFrom(topic)
160-
.pipe(filter(v => v.propertyName === name))
161-
.subscribe(v => cb(v.value as T)));
175+
.pipe(filter((v) => v.propertyName === name))
176+
.subscribe((v) => cb(v.value as T))
177+
);
162178
}
163179

164180
private subscribe<T extends CloudMessageValue>(topic: string, cb: OnMessageCallback<T>): Promise<void> {
@@ -168,9 +184,7 @@ export class CloudClient implements ICloudClient {
168184
this.callbacks[topic].push(cb);
169185

170186
this.subscriptions[topic] = this.subscriptions[topic] = [];
171-
this.subscriptions[topic].push(
172-
this.messagesFrom(topic)
173-
.subscribe(v => cb(v.value as T)));
187+
this.subscriptions[topic].push(this.messagesFrom(topic).subscribe((v) => cb(v.value as T)));
174188

175189
return resolve();
176190
} catch (err) {
@@ -183,7 +197,7 @@ export class CloudClient implements ICloudClient {
183197
return new Promise((resolve, reject) => {
184198
if (!this.connection) return reject(new Error('unsubscribe failed: no connection found'));
185199

186-
return this.connection.unsubscribe(topic, null, (err) => err ? reject() : resolve());
200+
return this.connection.unsubscribe(topic, null, (err) => (err ? reject() : resolve()));
187201
});
188202
}
189203

@@ -195,16 +209,14 @@ export class CloudClient implements ICloudClient {
195209
this.connection.subscribe(topic, (err) => {
196210
if (err) throw new Error(`subscription failed: ${err.toString()}`);
197211

198-
subscription = this.connection.messages
199-
.pipe(filter(v => v.topic === topic))
200-
.subscribe(v => subject.next(v));
212+
subscription = this.connection.messages.pipe(filter((v) => v.topic === topic)).subscribe((v) => subject.next(v));
201213
});
202214

203215
const originalMethod = subject.unsubscribe;
204216
subject.unsubscribe = () => {
205217
subscription.unsubscribe();
206218
originalMethod();
207-
}
219+
};
208220
return subject;
209221
}
210222
}

‎src/client/ICloudClient.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { IConnection } from "../connection/IConnection";
1+
import { IConnection } from '../connection/IConnection';
22

33
export type BaseCloudOptions = {
44
host?: string;
@@ -8,7 +8,7 @@ export type BaseCloudOptions = {
88
onConnected?: () => void;
99
onDisconnect?: (message?: any) => void;
1010
useCloudProtocolV2?: boolean;
11-
}
11+
};
1212

1313
export type BrowserOptions = {
1414
token: string;
@@ -48,4 +48,4 @@ export interface ICloudClient {
4848

4949
sendProperty<T extends CloudMessageValue>(thingId: string, name: string, value: T, timestamp?: number): Promise<void>;
5050
onPropertyValue<T extends CloudMessageValue>(thingId: string, name: string, cb: OnMessageCallback<T>): Promise<void>;
51-
}
51+
}

‎src/connection/Connection.ts

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
11
import jws from 'jws';
22
import mqtt from 'mqtt';
3-
import { Observable, Subject } from "rxjs";
3+
import { Observable, Subject } from 'rxjs';
44

55
import SenML from '../senML';
6-
import Utils from "../utils";
7-
import { CloudMessageValue } from "../client/ICloudClient";
8-
import { IConnection, CloudMessage, ConnectionOptions } from "./IConnection";
6+
import Utils from '../utils';
7+
import { CloudMessageValue } from '../client/ICloudClient';
8+
import { IConnection, CloudMessage, ConnectionOptions } from './IConnection';
99

1010
const BaseConnectionOptions: Partial<ConnectionOptions> = {
1111
clean: true,
1212
keepalive: 30,
1313
properties: {},
1414
protocolVersion: 4,
1515
connectTimeout: 30000,
16-
}
16+
};
1717

1818
export class Connection implements IConnection {
1919
public token: string;
2020
public messages: Observable<CloudMessage>;
21-
21+
2222
private _client: mqtt.MqttClient;
2323
private get client(): mqtt.MqttClient {
2424
return this._client;
2525
}
2626

2727
private set client(client: mqtt.MqttClient) {
2828
this._client = client;
29-
const messages = this.messages = new Subject<CloudMessage>();
29+
const messages = (this.messages = new Subject<CloudMessage>());
3030

3131
this._client.on('message', (topic, msg) => {
3232
if (topic.indexOf('/s/o') > -1) messages.next({ topic, value: msg.toString() });
3333
else this.messagesFrom(topic, msg).forEach((m) => messages.next(m));
3434
});
35-
};
36-
35+
}
36+
3737
public static async From(host: string, port: string | number, token: string): Promise<IConnection> {
3838
if (!token) throw new Error('connection failed: you need to provide a valid token');
3939
if (!host) throw new Error('connection failed: you need to provide a valid host (broker)');
@@ -46,16 +46,19 @@ export class Connection implements IConnection {
4646
};
4747

4848
const connection = new Connection();
49-
connection.client = mqtt.connect(`wss://${host}:${port}/mqtt`, { ...BaseConnectionOptions, ...options });
49+
connection.client = mqtt.connect(`wss://${host}:${port}/mqtt`, {
50+
...BaseConnectionOptions,
51+
...options,
52+
});
5053
connection.token = token;
51-
return connection
54+
return connection;
5255
}
5356

5457
public on(event: any, cb: any): IConnection {
5558
this.client.on(event, cb);
5659
return this;
5760
}
58-
public end(force?: boolean, opts?: Object, cb?: mqtt.CloseCallback): IConnection {
61+
public end(force?: boolean, opts?: Record<string, any>, cb?: mqtt.CloseCallback): IConnection {
5962
this.client.end(force, opts, cb);
6063
return this;
6164
}
@@ -94,16 +97,16 @@ export class Connection implements IConnection {
9497
if (previous === '') previous = current;
9598

9699
if (previous !== current) {
97-
messages.push({ topic, propertyName: previous, value: valueToSend })
100+
messages.push({ topic, propertyName: previous, value: valueToSend });
98101
previous = current;
99102
valueToSend = {};
100103
}
101104

102105
if (attribute) valueToSend[attribute] = value;
103-
else valueToSend = value
106+
else valueToSend = value;
104107
});
105108

106-
if (valueToSend !== {}) messages.push({ topic, propertyName: current, value: valueToSend })
109+
if (valueToSend !== {}) messages.push({ topic, propertyName: current, value: valueToSend });
107110

108111
return messages;
109112
}

‎src/connection/IConnection.ts

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,45 @@
1-
2-
import { Observable } from "rxjs";
1+
import { Observable } from 'rxjs';
32
import {
4-
IClientOptions, OnConnectCallback, OnMessageCallback, OnPacketCallback,
5-
OnErrorCallback, CloseCallback, IClientReconnectOptions, PacketCallback, IClientPublishOptions
3+
IClientOptions,
4+
OnConnectCallback,
5+
OnMessageCallback,
6+
OnPacketCallback,
7+
OnErrorCallback,
8+
CloseCallback,
9+
IClientReconnectOptions,
10+
PacketCallback,
11+
IClientPublishOptions,
612
} from 'mqtt';
713

8-
import { CloudMessageValue } from "../client/ICloudClient";
14+
import { CloudMessageValue } from '../client/ICloudClient';
915

1016
export type ConnectionOptions = IClientOptions;
11-
export type CloudMessage = { topic: string; propertyName?: string; value: CloudMessageValue };
17+
export type CloudMessage = {
18+
topic: string;
19+
propertyName?: string;
20+
value: CloudMessageValue;
21+
};
1222

1323
export interface IConnection {
1424
token?: string;
1525
messages?: Observable<CloudMessage>;
1626

17-
on(event: "connect", cb: OnConnectCallback): IConnection;
18-
on(event: "message", cb: OnMessageCallback): IConnection;
19-
on(event: "packetsend" | "packetreceive", cb: OnPacketCallback): IConnection;
20-
on(event: "error", cb: OnErrorCallback): IConnection;
27+
on(event: 'connect', cb: OnConnectCallback): IConnection;
28+
on(event: 'message', cb: OnMessageCallback): IConnection;
29+
on(event: 'packetsend' | 'packetreceive', cb: OnPacketCallback): IConnection;
30+
on(event: 'error', cb: OnErrorCallback): IConnection;
2131
on(event: string, cb: Function): IConnection;
22-
on(event: any, cb: any): IConnection
32+
on(event: any, cb: any): IConnection;
2333

24-
end(force?: boolean, opts?: Object, cb?: CloseCallback): IConnection
34+
end(force?: boolean, opts?: Record<string, any>, cb?: CloseCallback): IConnection;
2535

26-
reconnect(opts?: IClientReconnectOptions): IConnection
36+
reconnect(opts?: IClientReconnectOptions): IConnection;
2737

28-
unsubscribe(topic: string | string[], opts?: Object, callback?: PacketCallback): IConnection
38+
unsubscribe(topic: string | string[], opts?: Record<string, any>, callback?: PacketCallback): IConnection;
2939

3040
publish(topic: string, message: string | Buffer, opts: IClientPublishOptions, callback?: PacketCallback): IConnection;
3141
publish(topic: string, message: string | Buffer, callback?: PacketCallback): IConnection;
3242
publish(topic: any, message: any, opts?: any, callback?: any): IConnection;
3343

3444
subscribe(topic: any, callback?: any): IConnection;
3545
}
36-

‎src/http/HttpClientFactory.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@ type Fetch = (url: string, init?: any) => Promise<any>;
44

55
export class HttpClientFactory {
66
public static Create(fetch: Fetch): IHttpClient {
7-
return new class implements IHttpClient {
8-
post<T, P>(uri: string, body: P, headers?: { [key: string]: string; }): Promise<T> {
7+
return new (class implements IHttpClient {
8+
post<T, P>(uri: string, body: P, headers?: { [key: string]: string }): Promise<T> {
99
return this.execute(uri, 'post', body, headers);
1010
}
1111

12-
private async execute<T>(url: string, method: string, body?: any, headers?: { [key: string]: string; }): Promise<T> {
12+
private async execute<T>(
13+
url: string,
14+
method: string,
15+
body?: any,
16+
headers?: { [key: string]: string }
17+
): Promise<T> {
1318
const response = await fetch(url, { method, body, headers });
1419
const responseHeaders = this.mapFrom(response.headers);
1520

@@ -21,11 +26,11 @@ export class HttpClientFactory {
2126
else return payload;
2227
}
2328

24-
private mapFrom(headers: any): { [key: string]: string; } {
29+
private mapFrom(headers: any): { [key: string]: string } {
2530
const mapped = {};
2631
headers.forEach((v, n) => (mapped[n] = v));
2732
return mapped;
2833
}
29-
}
34+
})();
3035
}
3136
}

‎src/http/IHttpClient.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export interface IHttpClient {
2-
post<T, P = any>(uri: string, body: P, headers?: {[key: string]: string }): Promise<T>
3-
}
2+
post<T, P = any>(uri: string, body: P, headers?: { [key: string]: string }): Promise<T>;
3+
}

‎src/senML/index.ts

Lines changed: 66 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,78 @@
11
import CBOR, { SenML } from '@arduino/cbor-js';
22

3-
import Utils from "../utils";
4-
import { CloudMessageValue } from "../client/ICloudClient";
3+
import Utils from '../utils';
4+
import { CloudMessageValue } from '../client/ICloudClient';
55

66
function isPropertyValue(message: SenML | string[]): message is SenML {
77
return !!(message as SenML).n;
88
}
99

1010
function valueFrom(message: SenML | string[]): CloudMessageValue {
11-
return isPropertyValue(message)
12-
? message.v || message.vs || message.vb
13-
: message[2] || message[3] || message[4];
11+
return isPropertyValue(message) ? message.v || message.vs || message.vb : message[2] || message[3] || message[4];
1412
}
1513

1614
function nameFrom(property: SenML | string[]): string {
17-
return isPropertyValue(property) ? property.n : property[0]
15+
return isPropertyValue(property) ? property.n : property[0];
1816
}
1917

2018
function toString(value: SenML[], numericKeys?: boolean): string {
2119
const encoded = CBOR.encode(value, numericKeys);
2220
return Utils.arrayBufferToBase64(encoded);
23-
};
21+
}
2422

2523
function toCloudProtocolV2(cborValue: SenML): SenML {
2624
const cloudV2CBORValue = {};
2725
let cborLabel = null;
2826

2927
Object.keys(cborValue).forEach((label) => {
3028
switch (label) {
31-
case 'bn': cborLabel = -2; break;
32-
case 'bt': cborLabel = -3; break;
33-
case 'bu': cborLabel = -4; break;
34-
case 'bv': cborLabel = -5; break;
35-
case 'bs': cborLabel = -6; break;
36-
case 'bver': cborLabel = -1; break;
37-
case 'n': cborLabel = 0; break;
38-
case 'u': cborLabel = 1; break;
39-
case 'v': cborLabel = 2; break;
40-
case 'vs': cborLabel = 3; break;
41-
case 'vb': cborLabel = 4; break;
42-
case 'vd': cborLabel = 8; break;
43-
case 's': cborLabel = 5; break;
44-
case 't': cborLabel = 6; break;
45-
case 'ut': cborLabel = 7; break;
46-
default: cborLabel = label;
29+
case 'bn':
30+
cborLabel = -2;
31+
break;
32+
case 'bt':
33+
cborLabel = -3;
34+
break;
35+
case 'bu':
36+
cborLabel = -4;
37+
break;
38+
case 'bv':
39+
cborLabel = -5;
40+
break;
41+
case 'bs':
42+
cborLabel = -6;
43+
break;
44+
case 'bver':
45+
cborLabel = -1;
46+
break;
47+
case 'n':
48+
cborLabel = 0;
49+
break;
50+
case 'u':
51+
cborLabel = 1;
52+
break;
53+
case 'v':
54+
cborLabel = 2;
55+
break;
56+
case 'vs':
57+
cborLabel = 3;
58+
break;
59+
case 'vb':
60+
cborLabel = 4;
61+
break;
62+
case 'vd':
63+
cborLabel = 8;
64+
break;
65+
case 's':
66+
cborLabel = 5;
67+
break;
68+
case 't':
69+
cborLabel = 6;
70+
break;
71+
case 'ut':
72+
cborLabel = 7;
73+
break;
74+
default:
75+
cborLabel = label;
4776
}
4877

4978
cloudV2CBORValue[cborLabel] = cborValue[label];
@@ -54,7 +83,7 @@ function toCloudProtocolV2(cborValue: SenML): SenML {
5483

5584
function format(value: CloudMessageValue, name: string, timestamp: number, deviceId: string): SenML {
5685
const parsed: SenML = {};
57-
if (timestamp !== -1) parsed.bt = timestamp || new Date().getTime()
86+
if (timestamp !== -1) parsed.bt = timestamp || new Date().getTime();
5887
parsed.n = name;
5988

6089
if (deviceId) {
@@ -68,18 +97,25 @@ function format(value: CloudMessageValue, name: string, timestamp: number, devic
6897
return parsed;
6998
}
7099

71-
function parse(name: string, value: CloudMessageValue, timestamp: number, useCloudProtocolV2: boolean, deviceId: string): SenML | SenML[] {
100+
function parse(
101+
name: string,
102+
value: CloudMessageValue,
103+
timestamp: number,
104+
useCloudProtocolV2: boolean,
105+
deviceId: string
106+
): SenML | SenML[] {
72107
if (timestamp && !Number.isInteger(timestamp)) throw new Error('Timestamp must be Integer');
73108
if (name === undefined || typeof name !== 'string') throw new Error('Name must be a valid string');
74109

75-
if (Utils.isObject(value)) return Object.keys(value)
76-
.map((key, i) => format(value[key], `${name}:${key}`, i === 0 ? timestamp : -1, i === 0 ? deviceId : undefined))
77-
.map((cborValue) => useCloudProtocolV2 ? toCloudProtocolV2(cborValue) : cborValue);
110+
if (Utils.isObject(value))
111+
return Object.keys(value)
112+
.map((key, i) => format(value[key], `${name}:${key}`, i === 0 ? timestamp : -1, i === 0 ? deviceId : undefined))
113+
.map((cborValue) => (useCloudProtocolV2 ? toCloudProtocolV2(cborValue) : cborValue));
78114

79115
let cborValue = format(value, name, timestamp, deviceId);
80116
if (useCloudProtocolV2) cborValue = toCloudProtocolV2(cborValue);
81117
return cborValue;
82-
};
118+
}
83119

84120
export default {
85121
CBOR,
@@ -89,4 +125,4 @@ export default {
89125
nameFrom,
90126
isPropertyValue,
91127
toCloudProtocolV2,
92-
}
128+
};

‎src/utils/index.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { CloudMessageValue } from "../client/ICloudClient";
1+
import { CloudMessageValue } from '../client/ICloudClient';
22

33
class ArduinoCloudError extends Error {
44
constructor(public code: number, message: string) {
@@ -12,19 +12,19 @@ class ArduinoCloudError extends Error {
1212
}
1313

1414
function isObject(value: CloudMessageValue): value is object {
15-
return typeof (value) === "object";
15+
return typeof value === 'object';
1616
}
1717

1818
function isNumber(value: CloudMessageValue): value is number {
19-
return typeof (value) === "number";
19+
return typeof value === 'number';
2020
}
2121

2222
function isString(value: CloudMessageValue): value is string {
23-
return typeof (value) === "string";
23+
return typeof value === 'string';
2424
}
2525

2626
function isBoolean(value: CloudMessageValue): value is boolean {
27-
return typeof (value) === "boolean";
27+
return typeof value === 'boolean';
2828
}
2929

3030
function isArray<T>(value: CloudMessageValue): value is T[] {
@@ -41,9 +41,9 @@ function toArrayBuffer(buf: { length: number }): ArrayBuffer {
4141
}
4242

4343
function toBuffer(ab: ArrayBuffer): Buffer {
44-
var buffer = new Buffer(ab.byteLength);
45-
var view = new Uint8Array(ab);
46-
for (var i = 0; i < buffer.length; ++i) {
44+
const buffer = new Buffer(ab.byteLength);
45+
const view = new Uint8Array(ab);
46+
for (let i = 0; i < buffer.length; ++i) {
4747
buffer[i] = view[i];
4848
}
4949
return buffer;
@@ -57,7 +57,7 @@ function arrayBufferToBase64(buf: ArrayBuffer): string {
5757
binary += String.fromCharCode(bytes[i]);
5858
}
5959
return window.btoa(binary);
60-
};
60+
}
6161

6262
export default {
6363
ArduinoCloudError,
@@ -68,5 +68,5 @@ export default {
6868
isArray,
6969
toArrayBuffer,
7070
toBuffer,
71-
arrayBufferToBase64
72-
};
71+
arrayBufferToBase64,
72+
};

0 commit comments

Comments
 (0)
Please sign in to comment.