1 |
import { dot, object } from "dot-object"; |
2 |
import { body } from "express-validator"; |
3 |
import KeyValuePair from "../../types/KeyValuePair"; |
4 |
import Controller from "../Controller"; |
5 |
import RequireAuth from "../middleware/RequireAuth"; |
6 |
import ValidatorError from "../middleware/ValidatorError"; |
7 |
import Request from "../Request"; |
8 |
|
9 |
export default class ConfigController extends Controller { |
10 |
globalMiddleware(): Function[] { |
11 |
return [RequireAuth, ValidatorError]; |
12 |
} |
13 |
|
14 |
middleware(): KeyValuePair<Function[]> { |
15 |
return { |
16 |
update: [ |
17 |
body(["config"]).isObject() |
18 |
] |
19 |
}; |
20 |
} |
21 |
|
22 |
public async index(request: Request) { |
23 |
const { id } = request.params; |
24 |
|
25 |
if (!request.user?.guilds.includes(id)) { |
26 |
return this.response({ error: "You don't have permission to access configuration of this guild." }, 403); |
27 |
} |
28 |
|
29 |
if (id === "global" || !this.client.config.props[id]) { |
30 |
return this.response({ error: "No configuration found for the given guild ID" }, 404); |
31 |
} |
32 |
|
33 |
return this.client.config.props[id]; |
34 |
} |
35 |
|
36 |
public async update(request: Request) { |
37 |
const { id } = request.params; |
38 |
const { config } = request.body; |
39 |
const currentConfigDotObject = dot(this.client.config.props[id]); |
40 |
const newConfigDotObject = {...currentConfigDotObject}; |
41 |
|
42 |
console.log("Input: ", config); |
43 |
|
44 |
for (const configKey in config) { |
45 |
if (!(configKey in currentConfigDotObject)) { |
46 |
return { error: `The key '${configKey}' is not allowed` }; |
47 |
} |
48 |
|
49 |
if (typeof config[configKey] !== typeof currentConfigDotObject[configKey] || (config[configKey] !== null && currentConfigDotObject[configKey] === null) || (config[configKey] === null && currentConfigDotObject[configKey] !== null)) { |
50 |
return { error: `The key '${configKey}' has incompatible value type '${config[configKey] === null ? 'null' : typeof config[configKey]}'` }; |
51 |
} |
52 |
|
53 |
newConfigDotObject[configKey] = config[configKey]; |
54 |
console.log("Updating: ", configKey, config[configKey], newConfigDotObject[configKey]); |
55 |
} |
56 |
|
57 |
console.log("Output: ", newConfigDotObject); |
58 |
|
59 |
this.client.config.props[id] = object({...newConfigDotObject}); |
60 |
this.client.config.write(); |
61 |
|
62 |
return { message: "Configuration updated", previous: currentConfigDotObject, new: newConfigDotObject }; |
63 |
} |
64 |
} |