优化保存恢复功能

This commit is contained in:
锦恢 2024-10-18 20:26:11 +08:00
parent d77755a7dd
commit 18ef80557d
3 changed files with 33 additions and 17 deletions

3
src/global.ts Normal file
View File

@ -0,0 +1,3 @@
// 测试项目部署请看 README.md
export const rootPath = '../digital-vcd-render/public';

View File

@ -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('<h1>Hello, World!</h1><br><img src="https://picx.zhimg.com/v2-b4251de7d2499e942c7ebf447a90d2eb_l.jpg"/>');
});
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, () => {

27
src/save-view.ts Normal file
View File

@ -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<string, any>();
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');
}
}