90 lines
2.7 KiB
TypeScript
90 lines
2.7 KiB
TypeScript
import { CustomError } from '@kevisual/router';
|
|
import { app } from '../../app.ts';
|
|
import { PageModel } from './models/index.ts';
|
|
import { AppListModel, AppModel } from '../../routes/app-manager/index.ts';
|
|
import { cachePage, getZip } from './module/cache-file.ts';
|
|
import { uniqBy } from 'es-toolkit';
|
|
import semver from 'semver';
|
|
|
|
app
|
|
.route({
|
|
path: 'page',
|
|
key: 'publish',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
const { data, id, publish, ...rest } = ctx.query.data;
|
|
let needUpdate = { ...rest };
|
|
if (data) {
|
|
needUpdate = { ...needUpdate, data };
|
|
}
|
|
if (publish) {
|
|
needUpdate = { ...needUpdate, publish };
|
|
}
|
|
if (!id) {
|
|
throw new CustomError('id is required');
|
|
}
|
|
const page = await PageModel.findByPk(id);
|
|
if (!page) {
|
|
throw new CustomError('page not found');
|
|
}
|
|
await page.update(needUpdate);
|
|
|
|
const _publish = page.publish || {};
|
|
if (!_publish.key) {
|
|
throw new CustomError('publish key is required');
|
|
}
|
|
try {
|
|
const { key, description } = _publish;
|
|
const version = _publish.version || '0.0.0';
|
|
let app = await AppModel.findOne({ where: { key, uid: tokenUser.id } });
|
|
if (!app) {
|
|
app = await AppModel.create({ title: key, key, uid: tokenUser.id, description, user: tokenUser.username });
|
|
}
|
|
const _version = semver.inc(version, 'patch');
|
|
let appList = await AppListModel.findOne({ where: { key, version: _version, uid: tokenUser.id } });
|
|
if (!appList) {
|
|
appList = await AppListModel.create({ key, version: _version, uid: tokenUser.id, data: {} });
|
|
}
|
|
// 上传文件
|
|
const res = await cachePage(page, { tokenUser, key, version: _version });
|
|
const appFiles = appList?.data?.files || [];
|
|
const newFiles = uniqBy([...appFiles, ...res], (item) => item.name);
|
|
appList.data = {
|
|
...appList?.data,
|
|
files: newFiles,
|
|
};
|
|
await appList.save();
|
|
await page.update({ publish: { ..._publish, id: app.id, version: _version } });
|
|
ctx.body = page;
|
|
} catch (e) {
|
|
console.log('error', e);
|
|
throw new CustomError(e.message || 'publish error');
|
|
}
|
|
})
|
|
.addTo(app);
|
|
|
|
app
|
|
.route({
|
|
path: 'page',
|
|
key: 'download',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
const { id } = ctx.query;
|
|
const page = await PageModel.findByPk(id);
|
|
if (!page) {
|
|
throw new CustomError('page not found');
|
|
}
|
|
try {
|
|
const files = await getZip(page, { tokenUser });
|
|
ctx.body = files;
|
|
} catch (e) {
|
|
console.log('error', e);
|
|
throw new CustomError(e.message || 'download error');
|
|
}
|
|
})
|
|
.addTo(app);
|