/[sudobot]/trunk/src/api/controllers/ConfigController.ts
ViewVC logotype

Diff of /trunk/src/api/controllers/ConfigController.ts

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 368 by rakin, Mon Jul 29 17:29:49 2024 UTC revision 415 by rakin, Mon Jul 29 17:30:07 2024 UTC
# Line 1  Line 1 
1    /**
2    * This file is part of SudoBot.
3    *
4    * Copyright (C) 2021-2022 OSN Inc.
5    *
6    * SudoBot is free software; you can redistribute it and/or modify it
7    * under the terms of the GNU Affero General Public License as published by
8    * the Free Software Foundation, either version 3 of the License, or
9    * (at your option) any later version.
10    *
11    * SudoBot is distributed in the hope that it will be useful, but
12    * WITHOUT ANY WARRANTY; without even the implied warranty of
13    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14    * GNU Affero General Public License for more details.
15    *
16    * You should have received a copy of the GNU Affero General Public License
17    * along with SudoBot. If not, see <https://www.gnu.org/licenses/>.
18    */
19    
20  import { dot, object } from "dot-object";  import { dot, object } from "dot-object";
21  import { body } from "express-validator";  import { body } from "express-validator";
22  import KeyValuePair from "../../types/KeyValuePair";  import KeyValuePair from "../../types/KeyValuePair";
# Line 5  import Controller from "../Controller"; Line 24  import Controller from "../Controller";
24  import RequireAuth from "../middleware/RequireAuth";  import RequireAuth from "../middleware/RequireAuth";
25  import ValidatorError from "../middleware/ValidatorError";  import ValidatorError from "../middleware/ValidatorError";
26  import Request from "../Request";  import Request from "../Request";
27    import merge from 'ts-deepmerge';
28    
29  export default class ConfigController extends Controller {  export default class ConfigController extends Controller {
30      globalMiddleware(): Function[] {      globalMiddleware(): Function[] {
# Line 19  export default class ConfigController ex Line 39  export default class ConfigController ex
39          };          };
40      }      }
41    
42        private zodSchema(id: string) {
43            const config = this.client.config.props[id];
44            return this.client.config.schema(config);
45        }
46    
47      public async index(request: Request) {      public async index(request: Request) {
48          const { id } = request.params;          const { id } = request.params;
49    
# Line 35  export default class ConfigController ex Line 60  export default class ConfigController ex
60    
61      public async update(request: Request) {      public async update(request: Request) {
62          const { id } = request.params;          const { id } = request.params;
63          const { config } = request.body;          const { config: origconfig } = request.body;
64    
65            console.log(origconfig);        
66    
67          console.log(config);                  try {
68                const currentConfigDotObject = this.client.config.props[id];
69        
70                console.log("Current config: ", currentConfigDotObject);
71    
72                const result = this.zodSchema(id).safeParse(object(origconfig));
73    
74                if (!result?.success) {
75                    return this.response({ error: "The data schema does not match.", error_type: 'validation', errors: result.error.errors }, 422);
76                }
77    
78          const currentConfigDotObject = dot(this.client.config.props[id]);              const config = result.data;
79          const newConfigDotObject = {...currentConfigDotObject};              const newConfig = merge.withOptions({ mergeArrays: false }, currentConfigDotObject, config);
80                const result2 = this.zodSchema(id).safeParse(newConfig);
81          console.log("Input: ", config);  
82                if (!result2?.success) {
83          for (const configKey in config) {                  console.log(result2.error.errors);                
84              if (typeof currentConfigDotObject[configKey] === 'undefined') {                  return this.response({ error: 'Internal Server Error (500)', error_type: 'internal' }, 500);
                 return this.response({ error: `The key '${configKey}' is not allowed` }, 422);  
85              }              }
86    
87              if (config[configKey] !== null && config[configKey] !== null && typeof config[configKey] !== typeof currentConfigDotObject[configKey]) {              console.log('Final', newConfig);
88                  console.log(typeof config[configKey], typeof currentConfigDotObject[configKey]);                  this.client.config.props[id] = newConfig;
89                this.client.config.write();      
90                return { message: "Configuration updated", previous: dot(currentConfigDotObject), new: dot(this.client.config.props[id]) };    
91            }
92            catch (e) {
93                console.log(e);
94                return this.response({ error: 'Internal Server Error', error_type: 'internal' }, 500);
95            }
96        }
97    
98        public async update2(request: Request) {
99            const { id } = request.params;
100            const { config: origconfig } = request.body;
101    
102            console.log(origconfig);        
103    
104            try {
105                const currentConfigDotObject = dot(this.client.config.props[id]);
106                let newConfigDotObject = {...currentConfigDotObject};
107        
108                console.log("Current config: ", currentConfigDotObject);
109    
110                const result = this.zodSchema(id).safeParse(object({...origconfig}));
111    
112                if (!result?.success) {
113                    return this.response({ error: "The data schema does not match.", error_type: 'validation', errors: result.error.errors }, 422);
114                }
115    
116                const config = result.data;
117    
118                console.log(config);            
119    
120                for (const key in config) {
121                    const configKey = key as keyof typeof config;
122                    const regexMatched = /(.+)\[\d+\]/g.test(configKey);
123                                    
124                  if (typeof currentConfigDotObject[configKey] === 'number' && typeof config[configKey] === 'string') {                  if (typeof currentConfigDotObject[configKey] === 'undefined' && !regexMatched) {
125                      const int = parseInt(config[configKey]);                      console.log(configKey, config[configKey]);
126                        
127                        if (currentConfigDotObject[configKey] instanceof Array && config[configKey] instanceof Array) {
128                            console.log('Array');                        
129                        }
130                        else
131                            return this.response({ error: `The key '${configKey}' is not allowed` }, 422);
132                    }
133    
134                      if (int !== NaN) {                  if (!regexMatched && config[configKey] !== null && config[configKey] !== null && typeof config[configKey] !== typeof currentConfigDotObject[configKey]) {
135                          newConfigDotObject[configKey] = int;                      console.log(typeof config[configKey], typeof currentConfigDotObject[configKey]);    
136                          console.log("Updating: ", configKey, config[configKey], newConfigDotObject[configKey]);                      
137                          continue;                      if (typeof currentConfigDotObject[configKey] === 'number' && typeof config[configKey] === 'string') {
138                      }                          const int = parseInt(config[configKey]!.toString());
139    
140                            if (int !== NaN) {
141                                newConfigDotObject[configKey] = int;
142                                console.log("Updating: ", configKey, config[configKey], newConfigDotObject[configKey]);
143                                continue;
144                            }
145                        }
146                        
147                        return this.response({ error: `The key '${configKey}' has incompatible value type '${config[configKey] === null ? 'null' : typeof config[configKey]}'` }, 422);
148                  }                  }
149                    
150                  return this.response({ error: `The key '${configKey}' has incompatible value type '${config[configKey] === null ? 'null' : typeof config[configKey]}'` }, 422);                  console.log("Updating: ", configKey, config[configKey], newConfigDotObject[configKey]);
151              }              }
152    
153              newConfigDotObject[configKey] = config[configKey];              const newObj = object({...newConfigDotObject});
154              console.log("Updating: ", configKey, config[configKey], newConfigDotObject[configKey]);              const configObj = object({...config});
         }  
155    
156          console.log("Output: ", newConfigDotObject);              // console.log("Newobj", newObj);
157                // console.log("Configobj", configObj);
158    
159          this.client.config.props[id] = object({...newConfigDotObject});              newConfigDotObject = merge.withOptions({ mergeArrays: false }, newObj, configObj);
160          this.client.config.write();              console.log("Output: ", newConfigDotObject);
161    
162          return { message: "Configuration updated", previous: currentConfigDotObject, new: newConfigDotObject };              this.client.config.props[id] = newConfigDotObject;
163                this.client.config.write();
164    
165                return { message: "Configuration updated", previous: currentConfigDotObject, new: dot(this.client.config.props[id]) };
166            }
167            catch (e) {
168                console.log(e);
169                return this.response({ error: 'Internal Server Error', error_type: 'internal' }, 500);
170            }
171      }      }
172  }  }

Legend:
Removed from v.368  
changed lines
  Added in v.415

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26