card_svr/src/common/DataParser.ts
2020-12-03 11:42:30 +08:00

84 lines
2.6 KiB
TypeScript

import * as jetpack from "fs-jetpack";
import {singleton} from "./Singleton";
import {GameEnv} from "../cfg/GameEnv";
import {BaseConst} from "../constants/BaseConst";
const $cfg = new Map();
const jsonPath = 'configs';
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]) {
console.warn(`配置${key}的数据有误,唯一标识 ${idkey} 值为0或者没有${idkey}`);
continue;
}
let to = new CfgCreator();
to.decode(obj);
if (dict.has(to.id)) {
console.warn(`配置${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);
}
}
}
singleton(GameEnv).init($cfg.get(BaseConst.COMPOUND));
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;
}