Passed
Push — develop ( f6e8aa...01efa5 )
by Bjarn
01:34 queued 12s
created

SubdomainController.execute   A

Complexity

Conditions 5

Size

Total Lines 21
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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