import type { App, RouteContext } from '@kevisual/router'; import { DataTypes, Model } from 'sequelize'; type AppContext = { import: any; sequelize: any; }; type Ctx = RouteContext; class AppModel extends Model { declare id: string; declare title: string; declare description: string; declare cover: string; declare url: string; declare share: boolean; declare tags: string[]; declare uid: string; declare username: string; } export const getModel = async (ctx: Ctx) => { const sequelize = ctx.sequelize; if (!sequelize) { ctx.throw?.('sequelize instance not found'); } AppModel.init( { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, cover: { type: DataTypes.TEXT, allowNull: true, defaultValue: '', }, title: { type: DataTypes.TEXT, allowNull: false, defaultValue: '', }, description: { type: DataTypes.TEXT, allowNull: true, }, url: { type: DataTypes.TEXT, allowNull: false, }, share: { type: DataTypes.BOOLEAN, defaultValue: false, }, tags: { type: DataTypes.JSONB, defaultValue: [], }, uid: { type: DataTypes.UUID, allowNull: false, }, username: { type: DataTypes.TEXT, allowNull: false, defaultValue: '', }, }, { sequelize, modelName: 'apps_demo', }, ); return AppModel; }; /** * 初始化模型 * @param ctx */ export const initModel = async (ctx: RouteContext) => { try { const AppModel = await getModel(ctx); const res = await AppModel.sync({ alter: true }); ctx.body = 'success'; } catch (error) { console.error(error); ctx.throw?.(error.message); } }; export const render = (app: App) => { app .route({ path: 'apps-demo', key: 'init', middleware: ['auth'], }) .define(initModel) .addTo(app); app .route({ path: 'apps-demo', key: 'list', }) .define(async (ctx) => { const AppModel = await getModel(ctx); const res = await AppModel.findAll(); ctx.body = res; }) .addTo(app); app .route({ path: 'apps-demo', key: 'delete', }) .define(async (ctx) => { ctx.body = 'success'; }) .addTo(app); app .route({ path: 'apps-demo', key: 'update', }) .define(async (ctx) => { ctx.body = 'update success'; }) .addTo(app); };