Passed
Pull Request — master (#2)
by André
01:32
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
'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
	sourceConfiguration(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
		callback(input, error)
56
	}
57
58
59
	paramConfiguration(input, callback)  {
60
61
		let error = null
62
63
		if ( !input.params ) {
64
			if ( !error ) {
65
				error = new Error('The parameters are not been set.')
66
			}
67
		} else {
68
			if ( !input.params.payload ) {
69
				if ( !error ) {
70
					error = new Error('The parameter payload has not been set.')
71
				}
72
			} else {
73
				input.params.payload.toString()
74
			}
75
76
			if ( ![0, 1, 2].includes(input.params.qos) ) {
77
				input.params.qos = 2
78
			}
79
		}
80
81
		callback(input, error)
82
	}
83
84
}
85
86
module.exports = new Validate
87