Passed
Pull Request — master (#2)
by André
03:13 queued 01:18
created

validate.js ➔ sourceConfiguration   F

Complexity

Conditions 14
Paths 810

Size

Total Lines 45
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 25
c 1
b 0
f 0
nc 810
dl 0
loc 45
rs 3.6
nop 2

How to fix   Complexity   

Complexity

Complex classes like validate.js ➔ sourceConfiguration often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
12
		let error = null
13
14
		if ( !input.source.url ) {
15
			if ( !error ) {
16
				error = new Error('URL for MQTT broker has not been set.')
17
			}
18
		}
19
20
		if ( !this.url(input.source.url) ) {
21
			if ( !error ) {
22
				error = new Error('Your defined URL is invalid. It should start with mqtt://')
23
			}
24
		}
25
26
		let port = Number.parseInt(input.source.port)
27
		if ( Number.isNaN(port) ) {
28
			input.source.port = 1883
29
		} else {
30
			input.source.port = port
31
		}
32
33
		if ( !input.source.username ) {
34
			if ( !error ) {
35
				error = new Error('The user name for MQTT broker has not been set.')
36
			}
37
		}
38
39
		if ( !input.source.password ) {
40
			if ( !error ) {
41
				error = new Error('The password for MQTT broker has not been set.')
42
			}
43
		}
44
45
		if ( !input.source.topic && !input.params.topic ) {
46
			if ( !error ) {
47
				error = new Error('The parameter topic has not been set.')
48
			}
49
		} else if ( input.params ) {
50
			input.source.topic = input.params.topic || input.source.topic
51
		}
52
53
		callback(input, error)
54
	}
55
56
57
	paramConfiguration (input, callback) {
58
59
		let error = null
60
61
		if ( !input.params ) {
62
			if ( !error ) {
63
				error = new Error('The parameters are not been set.')
64
			}
65
		} else {
66
			if ( !input.params.payload ) {
67
				if ( !error ) {
68
					error = new Error('The parameter payload has not been set.')
69
				}
70
			} else {
71
				input.params.payload.toString()
72
			}
73
74
			if ( ![0, 1, 2].includes(input.params.qos) ) {
75
				input.params.qos = 2
76
			}
77
		}
78
79
		callback(input, error)
80
	}
81
82
}
83
84
module.exports = new Validate
85