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