120 lines
2.8 KiB
TypeScript
120 lines
2.8 KiB
TypeScript
import { CustomError } from '@abearxiong/router';
|
|
import { AppModel, AppListModel } from './module/index.ts';
|
|
import { app } from '@/app.ts';
|
|
import { setExpire } from './revoke.ts';
|
|
|
|
app
|
|
.route({
|
|
path: 'user-app',
|
|
key: 'list',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
const list = await AppModel.findAll({
|
|
order: [['updatedAt', 'DESC']],
|
|
where: {
|
|
uid: tokenUser.id,
|
|
},
|
|
});
|
|
ctx.body = list;
|
|
return ctx;
|
|
})
|
|
.addTo(app);
|
|
|
|
app
|
|
.route({
|
|
path: 'user-app',
|
|
key: 'get',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
const id = ctx.query.id;
|
|
const { key } = ctx.query.data || {};
|
|
if (!id && !key) {
|
|
throw new CustomError('id is required');
|
|
}
|
|
if (id) {
|
|
const am = await AppModel.findByPk(id);
|
|
if (!am) {
|
|
throw new CustomError('app not found');
|
|
}
|
|
ctx.body = am;
|
|
} else {
|
|
const am = await AppModel.findOne({ where: { key, uid: tokenUser.id } });
|
|
if (!am) {
|
|
throw new CustomError('app not found');
|
|
}
|
|
ctx.body = am;
|
|
}
|
|
|
|
return ctx;
|
|
})
|
|
.addTo(app);
|
|
|
|
app
|
|
.route({
|
|
path: 'user-app',
|
|
key: 'update',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
|
|
const { data, id, ...rest } = ctx.query.data;
|
|
if (id) {
|
|
const app = await AppModel.findByPk(id);
|
|
if (app) {
|
|
const newData = { ...app.data, ...data };
|
|
const newApp = await app.update({ data: newData, ...rest });
|
|
ctx.body = newApp;
|
|
if (app.status !== 'running') {
|
|
setExpire(newApp.key, app.user);
|
|
}
|
|
} else {
|
|
throw new CustomError('app not found');
|
|
}
|
|
return;
|
|
}
|
|
if (!rest.key) {
|
|
throw new CustomError('key is required');
|
|
}
|
|
const findApp = await AppModel.findOne({ where: { key: rest.key, uid: tokenUser.id } });
|
|
if (findApp) {
|
|
throw new CustomError('key already exists');
|
|
}
|
|
const app = await AppModel.create({
|
|
data: { files: [] },
|
|
...rest,
|
|
uid: tokenUser.id,
|
|
user: tokenUser.username,
|
|
});
|
|
ctx.body = app;
|
|
return ctx;
|
|
})
|
|
.addTo(app);
|
|
|
|
app
|
|
.route({
|
|
path: 'user-app',
|
|
key: 'delete',
|
|
middleware: ['auth'],
|
|
})
|
|
.define(async (ctx) => {
|
|
const tokenUser = ctx.state.tokenUser;
|
|
const id = ctx.query.id;
|
|
if (!id) {
|
|
throw new CustomError('id is required');
|
|
}
|
|
const am = await AppModel.findByPk(id);
|
|
if (!am) {
|
|
throw new CustomError('app not found');
|
|
}
|
|
const list = await AppListModel.findAll({ where: { key: am.key, uid: tokenUser.id } });
|
|
await am.destroy({ force: true });
|
|
await Promise.all(list.map((item) => item.destroy({ force: true })));
|
|
return ctx;
|
|
})
|
|
.addTo(app);
|