import { CustomError } from '@kevisual/router'; import { app } from '../../app.ts'; import { ContainerModel, ContainerData, Container } from './models/index.ts'; import semver from 'semver'; import { uploadMinioContainer } from '../page/module/cache-file.ts'; const list = app.route({ path: 'container', key: 'list', middleware: ['auth'], }); list.run = async (ctx) => { const tokenUser = ctx.state.tokenUser; const list = await ContainerModel.findAll({ order: [['updatedAt', 'DESC']], where: { uid: tokenUser.id, }, }); ctx.body = list; return ctx; }; list.addTo(app); app .route({ path: 'container', key: 'get', }) .define(async (ctx) => { const id = ctx.query.id; if (!id) { throw new CustomError('id is required'); } ctx.body = await ContainerModel.findByPk(id); return ctx; }) .addTo(app); const add = app.route({ path: 'container', key: 'update', middleware: ['auth'], }); add.run = async (ctx) => { const tokenUser = ctx.state.tokenUser; const data = ctx.query.data; const _data: Container = { title: '', description: '', code: '', type: '', }; const container = { ..._data, ...data, }; let containerModel: any = null; if (container.id) { containerModel = await ContainerModel.findByPk(container.id); if (containerModel) { containerModel.update(container); await containerModel.save(); ctx.emit?.('pageEdit', { source: 'container', data: containerModel.toJSON(), operation: 'edit', }); } } else { try { containerModel = await ContainerModel.create({ ...container, source: '', sourceType: '', uid: tokenUser.id, }); } catch (e) { console.log('error', e); } console.log('containerModel', container); } ctx.body = containerModel; return ctx; }; add.addTo(app); const deleteRoute = app.route({ path: 'container', key: 'delete', }); deleteRoute.run = async (ctx) => { const id = ctx.query.id; const container = await ContainerModel.findByPk(id); if (container) { await container.destroy(); } ctx.body = container; return ctx; }; deleteRoute.addTo(app); app .route({ path: 'container', key: 'publish', // nextRoute: { path: 'resource', key: 'publishContainer' }, middleware: ['auth'], }) .define(async (ctx) => { const tokenUser = ctx.state.tokenUser; const { data, token } = ctx.query; const { id, publish } = data; if (!id) { throw new CustomError('id is required'); } const container = await ContainerModel.findByPk(id); if (!container) { throw new CustomError('container not found'); } container.publish = publish; await container.save(); const { title, description, key, version, fileName } = publish; ctx.body = container; if (!key || !version || !fileName) { return; } const uploadResult = await uploadMinioContainer({ key, tokenUser: ctx.state.tokenUser, version: version, code: container.code, filePath: fileName, }); await ctx.call({ path: 'app', key: 'uploadFiles', payload: { token, data: { appKey: key, version, files: [uploadResult], }, }, }); }) .addTo(app);