diff --git a/src/global.ts b/src/global.ts new file mode 100644 index 0000000..40cd2b2 --- /dev/null +++ b/src/global.ts @@ -0,0 +1,3 @@ + +// 测试项目部署请看 README.md +export const rootPath = '../digital-vcd-render/public'; \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 7a8c404..4dd47ee 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,12 +1,11 @@ -import * as path from 'path'; -import * as fs from 'fs'; + import express, { Request, Response } from 'express'; import morgan from 'morgan'; import cors from 'cors'; import bodyParser from 'body-parser'; -import { BSON } from 'bson'; +import { saveView } from './save-view'; const corsOptions = { // 一些旧版浏览器(如 IE11、各种 SmartTV)在 204 状态下会有问题 @@ -21,25 +20,12 @@ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(morgan('dev')); -// 测试项目部署请看 README.md -const rootPath = '../digital-vcd-render/public'; app.get('/', (req: Request, res: Response) => { res.send('

Hello, World!


'); }); -app.post('/save-view', async (req: Request, res: Response) => { - try { - const { file, payload } = req.body; - const savePath = path.join(rootPath, file); - const buffer = BSON.serialize(payload); - fs.writeFileSync(savePath, buffer); - res.send('success'); - } catch (error) { - console.log('error happen in /save-view, ' + error); - res.send('error'); - } -}) +app.post('/save-view', saveView); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { diff --git a/src/save-view.ts b/src/save-view.ts new file mode 100644 index 0000000..497003a --- /dev/null +++ b/src/save-view.ts @@ -0,0 +1,27 @@ +import { Request, Response } from 'express'; +import * as path from 'path'; +import * as fs from 'fs'; +import { BSON } from 'bson'; +import { rootPath } from './global'; + +const payloadCache = new Map(); + +export async function saveView(req: Request, res: Response) { + try { + const { file, payload } = req.body; + if (!payloadCache.has(file)) { + payloadCache.set(file, payload); + } + + const originPayload = payloadCache.get(file); + Object.assign(originPayload, payload); + + const savePath = path.join(rootPath, file); + const buffer = BSON.serialize(originPayload); + fs.writeFileSync(savePath, buffer); + res.send('success'); + } catch (error) { + console.log('error happen in /save-view, ' + error); + res.send('error'); + } +} \ No newline at end of file