corgi/src/common/DataParser.ts
2021-04-27 15:54:45 +08:00

82 lines
2.1 KiB
TypeScript

import * as jetpack from 'fs-jetpack'
import { BaseConst } from '../constants/BaseConst'
import { error } from './Debug'
const $cfg = new Map()
const jsonPath = 'config'
export var DataParser = (function () {
const parsers: { [index: string]: ConfigDataParser } = {}
return {
regParser,
regCommonParser(key: string, CfgCreator: { new(): Cfg }, idkey = 'id') {
regParser(key, (data: any[]): any => {
if (!data) return
let dict = new Map()
for (let i = 0, len = data.length; i < len; i++) {
let obj = data[i]
if (!obj[idkey]) {
error(`配置${ key }的数据有误,唯一标识 ${ idkey } 值为0或者没有${ idkey }`)
continue
}
let to = new CfgCreator()
to.decode(obj)
if (dict.has(to.id)) {
error(`配置${ key }的数据有误,唯一标识 id 有重复值:${ to.id }`)
process.abort()
}
dict.set(to.id, to)
}
return dict
})
},
loadAll() {
let fileArr = jetpack.list(jsonPath)
for (let f of fileArr) {
let key = f.replace('_tbl.json', '')
let parser = parsers[key]
let json = jetpack.read(`${ jsonPath }/${ f }`, 'json')
if (parser && json) {
if (Array.isArray(json)) {
let data = parser(json)
if (data) { // 支持一些void的情况
$cfg.set(key, data)
}
} else {
$cfg.set(key, json)
}
}
}
Object.assign(global, {
$cfg: $cfg
})
}
}
/**
* 注册配置解析
* @param key 配置的标识
* @param parser 解析器
*/
function regParser(key: string, parser: ConfigDataParser) {
parsers[key] = parser
}
})()
/**
* 配置数据解析函数
*/
export interface ConfigDataParser {
(data: any): any;
}
export interface Cfg {
/**
* 解析配置
* @param {*} data
* @param {*} [local] 没有接口,但是需要本地赋值的数据
*/
decode?: { (local?: any): void };
id?: number;
}