Passed
Push — master ( d06fb8...9f4cb8 )
by André
03:15 queued 01:29
created

Validate.sourceConfiguration   B

Complexity

Conditions 6

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 24
rs 8.6666
c 0
b 0
f 0
cc 6
1
class Validate {
2
3
	url (string) {
4
		/* eslint no-useless-escape: 0 */
5
		let regex = /(mqtt|mqtts|tcp|tls|ws|wss):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/
6
		var pattern = new RegExp(regex)
7
		return pattern.test(string)
8
	}
9
10
	sourceConfiguration (input, callback) {
11
		let error = null
12
13
		if (!input.source.url) {
14
			if (!error) {
15
				error = new Error('URL for MQTT broker has not been set.')
16
			}
17
		}
18
19
		if (!this.url(input.source.url)) {
20
			if (!error) {
21
				error = new Error('Your defined URL is invalid. It should start with mqtt://')
22
			}
23
		}
24
25
		let port = Number.parseInt(input.source.port)
26
		if (Number.isNaN(port)) {
27
			input.source.port = 1883
28
		} else {
29
			input.source.port = port
30
		}
31
32
		callback(input, error)
33
	}
34
35
	paramConfiguration (input, callback) {
36
		let error = null
37
38
		if (!input.hasOwnProperty('params')) {
39
			if (!error) {
40
				return error = new Error('The parameters are not been set.')
0 ignored issues
show
Unused Code introduced by
The assignment to variable error seems to be never used. Consider removing it.
Loading history...
Comprehensibility introduced by
Are you sure you want to assign to error here, or did you intend to make a comparison like error === new Error("The...ers are not been set.")?
Loading history...
41
			}
42
		} else {
43
			if (!input.params.topic) {
44
				if (!error) {
45
					error = new Error('The parameter topic has not been set.')
46
				}
47
			}
48
			if (!input.params.payload) {
49
				if (!error) {
50
					error = new Error('The parameter payload has not been set.')
51
				}
52
			}
53
54
			if (![0, 1, 2].includes(input.params.qos)) {
55
				input.params.qos = 1
56
			} else {
57
				input.params.qos.toString()
58
			}
59
		}
60
61
		callback(input, error)
62
	}
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
63
64
}
65
66
module.exports = new Validate
67