-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheditNginxConfig.ts
42 lines (30 loc) · 1.22 KB
/
editNginxConfig.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Parser from "@webantic/nginx-config-parser";
import { outputFile, pathExists, readFile } from "fs-extra";
import { join } from "path";
import { logger } from "@lib/logger";
import settings from "@utils/settings";
import { NginxConf } from "@models/nginx.conf";
type EditConfigFunction = (nginxConfig: NginxConf) => NginxConf;
/**
* Parses an existing `nginx.conf` and runs a callback to edit the configuration
* What the callback returns will be outputted to the `nginx.conf`
* @param editConfig A function that receives an object with the existing config or {} if it does not exist
*/
export const editNginxConfig = async (
editConfig: EditConfigFunction
): Promise<void> => {
const nginxPath = join(settings.nginxPath, "nginx.conf");
let oldConfig: NginxConf;
const parser = new Parser();
if (await pathExists(nginxPath)) {
const nginxConfig = await readFile(nginxPath, "utf-8");
const concatSplitStrings = nginxConfig.replace(/" '\n\s+'/g, " ");
oldConfig = parser.toJSON<NginxConf>(concatSplitStrings);
} else {
oldConfig = {};
logger.nginxConfNotFound({ nginxPath });
}
const edited = editConfig(oldConfig);
const config = parser.toConf<NginxConf>(edited);
await outputFile(nginxPath, config);
};