Total Complexity | 21 |
Complexity/F | 10.5 |
Lines of Code | 79 |
Function Count | 2 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | 'use strict' |
||
2 | |||
3 | |||
4 | class Validate { |
||
5 | |||
6 | url (string) { |
||
7 | let regex = /(mqtt|mqtts|tcp|tls|ws|wss):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/ |
||
8 | var pattern = new RegExp(regex) |
||
9 | return pattern.test(string) |
||
10 | } |
||
11 | |||
12 | configuration(input, callback) { |
||
13 | |||
14 | let error = null |
||
15 | |||
16 | if ( !input.source.url ) { |
||
17 | if ( !error ) { |
||
18 | error = new Error('URL for MQTT broker has not been set.') |
||
19 | } |
||
20 | } |
||
21 | |||
22 | if ( !this.url(input.source.url) ) { |
||
23 | if ( !error ) { |
||
24 | error = new Error('Your defined URL is invalid. It should start with mqtt://') |
||
25 | } |
||
26 | } |
||
27 | |||
28 | let port = Number.parseInt(input.source.port) |
||
29 | if ( Number.isNaN(port) ) { |
||
30 | input.source.port = 1883 |
||
31 | } else { |
||
32 | input.source.port = port |
||
33 | } |
||
34 | |||
35 | if ( !input.source.username ) { |
||
36 | if ( !error ) { |
||
37 | error = new Error('The user name for MQTT broker has not been set.') |
||
38 | } |
||
39 | } |
||
40 | |||
41 | if ( !input.source.password ) { |
||
42 | if ( !error ) { |
||
43 | error = new Error('The password for MQTT broker has not been set.') |
||
44 | } |
||
45 | } |
||
46 | |||
47 | if ( !input.source.topic && !input.params.topic ) { |
||
48 | if ( !error ) { |
||
49 | error = new Error('The parameter topic has not been set.') |
||
50 | } |
||
51 | } else if(input.params) { |
||
52 | input.source.topic = input.params.topic || input.source.topic |
||
53 | } |
||
54 | |||
55 | |||
56 | if ( !input.params ) { |
||
57 | if ( !error ) { |
||
58 | error = new Error('The parameters are not been set.') |
||
59 | } |
||
60 | } else { |
||
61 | if ( !input.params.payload ) { |
||
62 | if ( !error ) { |
||
63 | error = new Error('The parameter payload has not been set.') |
||
64 | } |
||
65 | } else { |
||
66 | input.params.payload.toString() |
||
67 | } |
||
68 | |||
69 | if ( ![0, 1, 2].includes(input.params.qos) ) { |
||
70 | input.params.qos = 0 |
||
71 | } |
||
72 | } |
||
73 | |||
74 | callback(input, error) |
||
75 | } |
||
76 | |||
77 | } |
||
78 | |||
79 | module.exports = new Validate |
||
80 |