|
| 1 | +import Router from '@koa/router' |
| 2 | +import path from 'path' |
| 3 | +import fs from 'fs-extra' |
| 4 | +import { ROOT_DIR } from './constants' |
| 5 | +import { spawnSync } from 'child_process' |
| 6 | +import { getMeta } from './controllers' |
| 7 | + |
| 8 | +const router = new Router() |
| 9 | + |
| 10 | +router.get('/', (ctx) => { |
| 11 | + ctx.body = 'Hello' |
| 12 | +}) |
| 13 | + |
| 14 | +router.get('/meta', async (ctx) => { |
| 15 | + ctx.body = await getMeta() |
| 16 | +}) |
| 17 | + |
| 18 | +router.get('/files/(.*)', async (ctx) => { |
| 19 | + const filepath = path.join(ROOT_DIR, ctx.params[0]) |
| 20 | + if (fs.existsSync(filepath)) { |
| 21 | + ctx.body = await fs.readFile(filepath, 'utf-8') |
| 22 | + } else { |
| 23 | + ctx.status = 404 |
| 24 | + } |
| 25 | +}) |
| 26 | + |
| 27 | +router.post('/files/(.*)', async (ctx) => { |
| 28 | + const filepath = path.join(ROOT_DIR, ctx.params[0]) |
| 29 | + await fs.ensureDir(path.dirname(filepath)) |
| 30 | + await fs.writeFile(filepath, ctx.request.body, 'utf-8') |
| 31 | + ctx.status = 200 |
| 32 | +}) |
| 33 | + |
| 34 | +router.post('/run/:trans', async (ctx) => { |
| 35 | + const name = ctx.params.trans |
| 36 | + const input = ctx.request.body |
| 37 | + const script = path.resolve(__dirname, 'transfrom.ts') |
| 38 | + |
| 39 | + const result = spawnSync('ts-node', ['-T', script, name], { |
| 40 | + input, |
| 41 | + encoding: 'utf-8', |
| 42 | + }) |
| 43 | + |
| 44 | + const { stderr, stdout } = result |
| 45 | + |
| 46 | + if (stderr) { |
| 47 | + ctx.body = `/* ERROR */\n\n${stderr}\n` |
| 48 | + } else { |
| 49 | + ctx.body = stdout |
| 50 | + } |
| 51 | +}) |
| 52 | + |
| 53 | +export { router } |
0 commit comments