增加配置读取

This commit is contained in:
zhl 2021-04-27 15:54:45 +08:00
parent eaec5fec7b
commit e21f4cd19f
10 changed files with 186 additions and 9 deletions

View File

@ -33,6 +33,7 @@
"fastify-helmet": "^5.0.3",
"fastify-jwt": "^2.2.0",
"fastify-plugin": "^3.0.0",
"fs-jetpack": "^4.1.0",
"iconv-lite": "^0.6.2",
"mime-types": "^2.1.27",
"mongoose": "5.10.3",

View File

@ -10,6 +10,7 @@ import {RouterMap} from 'decorators/router';
import {mongoose} from "@typegoose/typegoose";
import logger from 'logger/logger';
import config from 'config/config';
import { initData } from './common/GConfig'
const zReqParserPlugin = require('plugins/zReqParser');
@ -137,6 +138,7 @@ export class ApiServer {
self.registerRouter();
self.setErrHandler();
self.setFormatSend();
initData()
this.server.listen({port: config.api.port}, (err: any, address: any) => {
if (err) {
logger.log(err)

View File

@ -1,23 +1,28 @@
import BaseController from '../../common/base.controller'
import { role, router } from '../../decorators/router'
import { Puzzle } from '../../models/content/Puzzle'
import { PuzzleSession } from '../../models/match/PuzzleSession'
import { ZError } from '../../common/ZError'
class PuzzleController extends BaseController {
@role('anon')
@router('post /api/:accountid/puzzle/list')
async list(req, res) {
let { shop, level } = req.params
let { shop, level, accountid } = req.params
let count = 10
let records = await Puzzle.aggregate([
{ $match: { status: 1, is_hide: 0, deleted: 0 } },
{ $sample: { size: count } }
]).exec()
return records.map(o => {
let history = new PuzzleSession({ shop, level })
history.members = [accountid]
history.questions = records.map(o => o.id)
await history.save()
const results = records.map(o => {
let answers = []
for (let i = 1; i <=4; i++) {
if (o[`a${i}`]) {
answers.push(o[`a${i}`])
for (let i = 1; i <= 4; i++) {
if (o[`a${ i }`]) {
answers.push(o[`a${ i }`])
}
}
answers.randomSort()
@ -28,6 +33,10 @@ class PuzzleController extends BaseController {
type: 1
}
})
return {
session: history.id,
records: results
}
}
@role('anon')
@ -45,6 +54,6 @@ class PuzzleController extends BaseController {
if (type == 1) {
result = 0
}
return {result}
return { result }
}
}

81
src/common/DataParser.ts Normal file
View File

@ -0,0 +1,81 @@
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;
}

20
src/common/Debug.ts Normal file
View File

@ -0,0 +1,20 @@
import debug from 'debug';
debug.log = console.info.bind(console);
export const debugRoom = debug('jc:room');
export const msgLog = debug('jc:msg');
export const robotLog = debug('jc:robot');
export const assistLog = debug('jc:assist');
export const cardLog = debug('jc:card');
export const sysLog = debug('jc:sys');
export const matchlog = debug('jc:match');
export const error = debug('jc:error');
error.log = console.error.bind(console);

15
src/common/GConfig.ts Normal file
View File

@ -0,0 +1,15 @@
import {DataParser} from "./DataParser";
import {compound_vo} from "../config/parsers/compound_vo"
import {mission_vo} from "../config/parsers/mission_vo"
import { BaseConst } from '../constants/BaseConst'
export function initData() {
const rP = DataParser.regCommonParser.bind(DataParser);
rP(BaseConst.COMPOUND, compound_vo);
rP(BaseConst.MISSION, mission_vo);
DataParser.loadAll();
}

View File

@ -0,0 +1,4 @@
export class BaseConst{
public static readonly COMPOUND = 'compound'
public static readonly MISSION = 'mission'
}

12
src/global.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
export {}
declare global {
namespace NodeJS {
interface Global {
NODE_ENV: string
ROOT_PATH: string
$cfg: any
isProd: boolean
}
}
}

View File

@ -1,11 +1,29 @@
import { dbconn } from '../../decorators/dbconn'
import { getModelForClass, modelOptions } from '@typegoose/typegoose'
import { getModelForClass, modelOptions, prop } from '@typegoose/typegoose'
import { BaseModule } from '../Base'
@dbconn('second')
@modelOptions({ schemaOptions: { collection: 'question_category' } })
class PuzzleSessionClass extends BaseModule {
@prop({ type: () => [String] })
members: string[]
@prop({ type: () => [String] })
questions: string[]
@prop()
shop: string
@prop()
level: number
@prop()
room: string
@prop({default: 0})
status: number
}
export const PuzzleSession = getModelForClass(PuzzleSessionClass, { existingConnection: PuzzleSessionClass.db })

View File

@ -1024,6 +1024,14 @@ fs-extra@^8.1.0:
jsonfile "^4.0.0"
universalify "^0.1.0"
fs-jetpack@^4.1.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/fs-jetpack/-/fs-jetpack-4.1.0.tgz#d693fcffd3cedbd8829226967866b9e89f290f0f"
integrity sha512-h4nHLIcCaxnXfUWhwP+mLnar03R2DBlqicNvKJG44TJob8RV6GB8EKNwJgSaBeDAfqWhqq01y+Ao96vRwpXlPw==
dependencies:
minimatch "^3.0.2"
rimraf "^2.6.3"
fs.realpath@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
@ -1075,7 +1083,7 @@ getpass@^0.1.1:
dependencies:
assert-plus "^1.0.0"
glob@^7.1.1:
glob@^7.1.1, glob@^7.1.3:
version "7.1.6"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6"
integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==
@ -1515,7 +1523,7 @@ mime@^1.3.4:
resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1"
integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==
minimatch@^3.0.4:
minimatch@^3.0.2, minimatch@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==
@ -2022,6 +2030,13 @@ rfdc@^1.1.4, rfdc@^1.2.0:
resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.3.0.tgz#d0b7c441ab2720d05dc4cf26e01c89631d9da08b"
integrity sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==
rimraf@^2.6.3:
version "2.7.1"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec"
integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==
dependencies:
glob "^7.1.3"
safe-buffer@5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1:
version "5.1.2"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"