Passed
Push — main ( 379847...458a8f )
by Bjarn
02:40 queued 01:26
created

src/controllers/subdomainController.ts   A

Complexity

Total Complexity 13
Complexity/F 3.25

Size

Lines of Code 115
Function Count 4

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 80
dl 0
loc 115
rs 10
c 0
b 0
f 0
wmc 13
mnd 9
bc 9
fnc 4
bpm 2.25
cpm 3.25
noi 0

4 Functions

Rating   Name   Duplication   Size   Complexity  
A SubdomainController.addSubdomain 0 24 3
A SubdomainController.subdomainExists 0 6 2
A SubdomainController.deleteSubdomain 0 25 3
A SubdomainController.execute 0 21 5
1
import {readFileSync, writeFileSync} from 'fs'
2
import Nginx from '../services/nginx'
3
import {error, success, url} from '../utils/console'
4
import {getConfig, jaleSitesPath} from '../utils/jale'
5
6
class SubdomainController {
7
8
    serverNamesRegex = new RegExp('(?<=server_name \\s*).*?(?=\\s*;)', 'gi')
9
10
    execute = async (option: string, subdomain: string): Promise<void> => {
11
        if (option !== 'add' && option !== 'del') {
12
            error('Invalid option. Please use \'add\' or \'del\', followed by the subdomain.')
13
            return
14
        }
15
16
        const config = await getConfig()
17
        const project = process.cwd().substring(process.cwd().lastIndexOf('/') + 1)
18
        const hostname = `${project}.${config.tld}`
19
20
        let restartNginx = false
21
22
        if (option === 'add') {
23
            restartNginx = this.addSubdomain(subdomain, hostname)
24
        }
25
        else if (option === 'del') {
26
            restartNginx = this.deleteSubdomain(subdomain, hostname)
27
        }
28
29
        if (restartNginx)
30
            await (new Nginx()).reload()
31
    }
32
33
    /**
34
     * Check if the subdomain already exists in the vhost's Nginx configuration.
35
     *
36
     * @param subdomain
37
     * @param hostname
38
     */
39
    subdomainExists = (subdomain: string, hostname: string): boolean => {
40
        try {
41
            const vhostConfig = readFileSync(`${jaleSitesPath}/${hostname}.conf`, 'utf-8')
42
            return vhostConfig.includes(`${subdomain}.${hostname}`)
43
        } catch (e) {
44
            return false
45
        }
46
    }
47
48
    /**
49
     * Add a new subdomain to the vhost's Nginx configuration.
50
     *
51
     * @param subdomain
52
     * @param hostname
53
     */
54
    addSubdomain = (subdomain: string, hostname: string): boolean => {
55
        if (this.subdomainExists(subdomain, hostname)) {
56
            error(`Subdomain ${subdomain}.${hostname} already exists.`)
57
            return false
58
        }
59
60
        let vhostConfig = readFileSync(`${jaleSitesPath}/${hostname}.conf`, 'utf-8')
61
        const rawServerNames = this.serverNamesRegex.exec(vhostConfig)
62
63
        if (!rawServerNames) {
64
            return false // TODO: Catch this issue
65
        }
66
67
        const serverNames = rawServerNames[0].split(' ')
68
        serverNames.push(`${subdomain}.${hostname}`)
69
70
        // Replace the old server names with the server names including the new subdomain.
71
        vhostConfig = vhostConfig.replace(this.serverNamesRegex, serverNames.join(' '))
72
73
        writeFileSync(`${jaleSitesPath}/${hostname}.conf`, vhostConfig)
74
75
        success(`Added subdomain ${url(`${subdomain}.${hostname}`)}.`)
76
77
        return true
78
    }
79
80
    /**
81
     * Delete a subdomain from the vhost's Nginx configuration.
82
     *
83
     * @param subdomain
84
     * @param hostname
85
     */
86
    deleteSubdomain = (subdomain: string, hostname: string): boolean => {
87
        if (!this.subdomainExists(subdomain, hostname)) {
88
            error(`Subdomain ${url(`${subdomain}.${hostname}`)} does not exist.`)
89
            return false
90
        }
91
92
        let vhostConfig = readFileSync(`${jaleSitesPath}/${hostname}.conf`, 'utf-8')
93
94
        const rawServerNames = this.serverNamesRegex.exec(vhostConfig)
95
96
        if (!rawServerNames) {
97
            return false // TODO: Catch this issue
98
        }
99
        
100
        const serverNames = rawServerNames[0].split(' ')
101
        serverNames.splice(serverNames.indexOf(`${subdomain}.${hostname}`), 1)
102
103
        // Replace the old server names with the new list without the removed subdomain.
104
        vhostConfig = vhostConfig.replace(this.serverNamesRegex, serverNames.join(' '))
105
106
        writeFileSync(`${jaleSitesPath}/${hostname}.conf`, vhostConfig)
107
108
        success(`Removed subdomain ${subdomain}.${hostname}.`)
109
110
        return true
111
    }
112
113
}
114
115
export default SubdomainController