import { defaultData, Resource, ResourceModel } from './models/index.ts'; import { ContainerModel } from './../container/models/index.ts'; import { app } from '../../app.ts'; import { Op } from 'sequelize'; import { publishJsCode } from './lib/publish-minio.ts'; import { CustomError } from '@abearxiong/router'; app .route({ path: 'resource', key: 'publishContainer', idUsePath: true, }) .define(async (ctx) => { const container = ctx.state.container as ContainerModel; const publish = container.publish; const code = container.code; let { name, rid, description, version = '0.0.1' } = publish; const where = []; if (rid) { where.push({ id: rid }); } if (name) { where.push({ name }); } let resource = await ResourceModel.findOne({ where: { [Op.or]: where } }); let isCreate = false; if (!resource) { isCreate = true; resource = await ResourceModel.create({ name, description, version, source: 'container', sourceId: container.id, data: { ...defaultData, updatedAt: new Date().toISOString(), }, }); } publish.rid = publish.rid || resource.id; // TODO: check version const res = await publishJsCode({ name, version, code }); if (res.code === 200) { await container.update({ publish }); const { etag, versionId, path } = res.data; resource.version = version; const newData = { list: [], ...resource.data, }; newData.list.push({ etag, versionId, path, }); newData.lastestVersion = version; newData.updatedAt = new Date().toISOString(); resource.data = newData; await resource.save(); ctx.body = { resource, container, resourceIsNew: isCreate }; } else { throw new CustomError(res.message); } // await container.update({ publish }); }) .addTo(app);