import Router, { RouterContext } from 'koa-router' import directoryTree from 'directory-tree' import fs from 'fs' import path from 'path' import exportJson from './utils/exportJson' const formFileRouter = new Router() const formConfigTemplate = fs.readFileSync(path.resolve(__dirname, './template/formConfig.js')) export function createFormConfigFile(filePath: string): void { if (!filePath) { return } fs.writeFileSync(filePath, formConfigTemplate) } async function createConfigHandler(ctx: RouterContext) { const filePath = ctx.request.body.path if (!filePath) { return ctx.body = ctx.fail(null, 'path is required') } createFormConfigFile(filePath) ctx.body = ctx.ok() } async function getConfigHandler (ctx: RouterContext) { let formConfigPath: string = ctx.request.query.path if (!formConfigPath) { return ctx.body = ctx.fail('path is needed') } formConfigPath = path.resolve(ctx.legoOption.root, formConfigPath) const stat = fs.statSync(formConfigPath) if (!stat.isFile()) { return ctx.body = ctx.fail(`${formConfigPath} do not existed`) } delete require.cache[require.resolve(formConfigPath)] let form = require(formConfigPath) let data = { form, path: formConfigPath, formConfigPath, } ctx.body = ctx.ok(data) } async function getLegoConfigTreeHandler(ctx: RouterContext, next: any) { ctx.body = ctx.ok(directoryTree(ctx.legoOption.root)) next() } async function updateConfig(ctx: RouterContext) { let body = ctx.request.body let fileContent = exportJson(body.form) fs.writeFileSync(path.resolve(ctx.legoOption.root, body.path), fileContent) ctx.body = ctx.ok() } formFileRouter .get('/getConfig', getConfigHandler) .get('/getConfigTree', getLegoConfigTreeHandler) .post('/updateConfig', updateConfig) .post('/newConfig', createConfigHandler) export default formFileRouter