feat: optimize config loader

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2022-04-19 09:29:57 +08:00
parent 83cad2f52e
commit 46729b9cf0
20 changed files with 304 additions and 228 deletions

View File

@ -0,0 +1,65 @@
import * as fs from '@ccms/common/dist/fs'
import { PluginConfig, PluginConfigLoader } from './interfaces'
export class PluginFileConfig implements PluginConfig {
private loader: PluginConfigLoader
private file: string
constructor(loader: PluginConfigLoader, file: string, def = {}) {
this.loader = loader
this.file = file
if (fs.exists(file)) {
this.reload()
} else {
Object.assign(this, def)
}
this.initialize()
}
initialize() {
}
save() {
base.save(this.file, this.loader.dump(this))
}
reload() {
Object.assign(this, this.loader.load(base.read(this.file)))
}
}
export class PluginConfigFolder {
private loader: PluginConfigLoader
private folder: string
private configCache = new Map<string, PluginFileConfig>()
constructor(loader: PluginConfigLoader, folder: string) {
this.loader = loader
this.folder = folder
}
createConfig(path: string, def = {}) {
return new PluginFileConfig(this.loader, path, def)
}
getConfig(name: string, def = {}) {
let path = fs.concat(this.folder, name)
if (!this.configCache.has(path)) {
this.configCache.set(path, this.createConfig(path, def))
}
return this.configCache.get(path)
}
clear() {
this.configCache.clear()
}
save() {
this.configCache.forEach((config) => config.save())
}
reload() {
this.configCache.forEach((config) => config.reload())
}
}

View File

@ -0,0 +1,18 @@
export const PluginConfigLoader = Symbol.for('PluginConfigLoader')
export interface PluginConfigLoader {
type: string
load(content: string): any
dump(variable: any): string
}
export interface PluginConfig {
/**
* Save Config to File
*/
readonly save?: () => void
/**
* Reload Config from File
*/
readonly reload?: () => void
[key: string]: any
}

View File

@ -0,0 +1,18 @@
import { provideSingletonNamed } from '@ccms/container'
import { PluginConfigLoader } from '../interfaces'
const LOADER_TYPE_NAME = 'json'
@provideSingletonNamed(PluginConfigLoader, LOADER_TYPE_NAME)
export class JsonPluginConfig implements PluginConfigLoader {
type: string = LOADER_TYPE_NAME
load(content: string) {
return JSON.parse(content)
}
dump(variable: any): string {
return JSON.stringify(variable, undefined, 4)
}
}

View File

@ -0,0 +1,19 @@
import * as yaml from 'js-yaml'
import { provideSingletonNamed } from '@ccms/container'
import { PluginConfigLoader } from '../interfaces'
const LOADER_TYPE_NAME = 'yml'
@provideSingletonNamed(PluginConfigLoader, LOADER_TYPE_NAME)
export class YamlPluginConfig implements PluginConfigLoader {
type: string = LOADER_TYPE_NAME
load(content: string) {
return yaml.load(content)
}
dump(variable: any): string {
return yaml.dump(variable, { skipInvalid: true, lineWidth: 120 })
}
}