better code: config.set will accept an Updater callback
Massimo Melina committed
May 1, 2022 at 10:46 UTC
585d77803114b06a2912e09ab142d57e2c9c886b
2 files changed
+13
-8
server/src/adminApis.ts
+7
-6
@@ -178,18 +178,19 @@ export const adminApis: ApiHandlers = {
178
179
async set_plugin({ id, enabled, config }) {
180
assert(id, 'id')
181
- if (enabled !== undefined) {
182
- const a = enablePlugins.get()
183
- if (a.includes(id) !== enabled)
184
- enablePlugins.set( enabled ? [...a, id] : a.filter((x: string) => x !== id) )
185
- }
181
+ if (enabled !== undefined)
182
+ enablePlugins.set( arr =>
183
+ arr.includes(id) === enabled ? arr
184
+ : enabled ? [...arr, id]
185
+ : arr.filter((x: string) => x !== id)
186
+ )
187
if (config) {
188
const fields = getPluginConfigFields(id)
189
config = _.pickBy(config, (v, k) =>
190
v !== null && !same(v, fields?.[k]?.defaultValue))
191
if (_.isEmpty(config))
192
config = undefined
192
- pluginsConfig.set({ ...pluginsConfig.get(), [id]: config })
193
+ pluginsConfig.set(v => ({ ...v, [id]: config }))
194
}
195
return {}
196
},
server/src/config.ts
+6
-2
@@ -31,6 +31,7 @@ interface ConfigProps<T> {
31
}
32
export function defineConfig<T>(k: string, defaultValue?: T) {
33
configProps[k] = { defaultValue }
34
+ type Updater = (currentValue:T) => T
35
return {
36
key() {
37
return k
@@ -41,8 +42,11 @@ export function defineConfig<T>(k: string, defaultValue?: T) {
42
sub(cb: (v:T, was?:T)=>void) {
43
return subscribeConfig(k, cb)
44
},
44
- set(v: T) {
45
- return setConfig1(k, v)
45
+ set(v: T | Updater) {
46
+ if (typeof v === 'function')
47
+ this.set((v as Updater)(this.get()))
48
+ else
49
+ setConfig1(k, v)
50
}
51
}
52
}