import Router, {RouterContext} from 'koa-router' import fs from 'fs-extra' import path from 'path' import log from '../utils/log' import exportJson from './utils/exportJson'; const queryConfigRouter = new Router() const query_template_path = path.resolve(__dirname, './template/query-lego') export function createQueryConfig(configPath: string) { if (fs.existsSync(configPath)) { log.error(`配置文件${configPath}已存在`) return } fs.copySync(query_template_path, configPath) } async function getConfigHandler(ctx: RouterContext, next: any) { let configPath = ctx.request.query.path if (typeof configPath !== 'string' || !configPath) { throw new Error('path is required') } const absolutePath = path.resolve(ctx.legoOption.root, configPath) delete require.cache[absolutePath] ctx.body = ctx.ok({ form: require(absolutePath), path: absolutePath }) next() } async function updateConfigHandler(ctx: RouterContext, next: any) { const body = ctx.request.body const configPath: string = body.path const form = body.form const absolutePath: string = path.resolve(ctx.legoOption.root, configPath) ;['table', 'panel'].forEach((type: string) => { fs.writeFileSync( path.resolve(absolutePath, `${type}.lego.js`), exportJson(form[type]) ) }) ctx.body = ctx.ok() next() } async function createConfigHandler(ctx: RouterContext, next: any) { const formConfigPath: string = ctx.request.body.path const absolutePath = path.resolve(ctx.legoOption.root, formConfigPath) createQueryConfig(absolutePath) next() } queryConfigRouter .post('/getConfig', getConfigHandler) .post('/updateConfig', updateConfigHandler) .post('/createConfig', createConfigHandler) export default queryConfigRouter