121 lines
2.5 KiB
TypeScript

import { app } from '@/app.ts';
import { PackagesModel } from './models/index.ts';
import { Op } from 'sequelize';
import { CustomError } from '@kevisual/router';
app
.route({
path: 'packages',
key: 'list',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { uid } = tokenUser;
const { page = 1, pageSize = 999, search } = ctx.query;
const searchWhere = search ? { title: { [Op.like]: `%${search}%` } } : {};
const { rows: packages, count } = await PackagesModel.findAndCountAll({
where: {
uid,
...searchWhere,
},
limit: pageSize,
offset: (page - 1) * pageSize,
});
ctx.body = {
pagination: {
current: page,
pageSize,
total: count,
},
list: packages,
};
})
.addTo(app);
app
.route({
path: 'packages',
key: 'get',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { uid } = tokenUser;
const { id } = ctx.query;
if (!id) {
throw new CustomError('id is required');
}
const packages = await PackagesModel.findOne({
where: {
uid,
id,
},
});
if (!packages) {
throw new CustomError('not found data');
}
ctx.body = packages;
})
.addTo(app);
app
.route({
path: 'packages',
key: 'update',
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { uid } = tokenUser;
const { id, ...rest } = ctx.request.body;
let packages: PackagesModel;
if (!id) {
packages = await PackagesModel.create({
...rest,
uid,
});
} else {
packages = await PackagesModel.findOne({
where: {
uid,
id,
},
});
if (!packages) {
throw new CustomError('not found data');
}
await packages.update({
...rest,
});
}
ctx.body = packages;
})
.addTo(app);
app
.route({
path: 'packages',
key: 'delete',
middleware: ['auth'],
})
.define(async (ctx) => {
const tokenUser = ctx.state.tokenUser;
const { uid } = tokenUser;
const { id } = ctx.request.body;
if (!id) {
throw new CustomError('id is required');
}
const packages = await PackagesModel.findOne({
where: {
uid,
id,
},
});
if (!packages) {
throw new CustomError('not found data');
}
await packages.destroy();
ctx.body = packages;
})
.addTo(app);