Add validation to dependencies GET endpoint and update service logic

Introduces Joi validation for the GET /dependencies route using celebrate, ensuring request bodies conform to expected structure. Updates the DependenceService.dependencies method to handle type filtering more robustly and refines the search condition logic.
This commit is contained in:
涛之雨 2025-08-05 22:36:48 +08:00
parent 213ee53347
commit 3c1dc68ac9
No known key found for this signature in database
GPG Key ID: A38E8DF826ECA7E3
2 changed files with 34 additions and 24 deletions

View File

@ -8,7 +8,18 @@ const route = Router();
export default (app: Router) => { export default (app: Router) => {
app.use('/dependencies', route); app.use('/dependencies', route);
route.get('/', async (req: Request, res: Response, next: NextFunction) => { route.get(
'/',
celebrate({
body: Joi.array().items(
Joi.object({
searchValue: Joi.string().optional().allow(''),
type: Joi.string().optional().allow(''),
status: Joi.string().optional().allow(''),
}),
),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger'); const logger: Logger = Container.get('logger');
try { try {
const dependenceService = Container.get(DependenceService); const dependenceService = Container.get(DependenceService);
@ -18,7 +29,8 @@ export default (app: Router) => {
logger.error('🔥 error: %o', e); logger.error('🔥 error: %o', e);
return next(e); return next(e);
} }
}); },
);
route.post( route.post(
'/', '/',

View File

@ -98,34 +98,32 @@ export default class DependenceService {
searchValue, searchValue,
type, type,
status, status,
}: { searchValue: string; type: string; status: string }, }: {
searchValue: string;
type: keyof typeof DependenceTypes;
status: string;
},
sort: any = [], sort: any = [],
query: any = {}, query: any = {},
): Promise<Dependence[]> { ): Promise<Dependence[]> {
let condition = { let condition = query;
...query, if (type && ['nodejs', 'python3', 'linux'].includes(type)) {
type: DependenceTypes[type as any], condition.type = DependenceTypes[type];
}; } else condition.type = [0, 1, 2];
if (status) { if (status) {
condition.status = status.split(',').map(Number); condition.status = status.split(',').map(Number);
} }
if (searchValue) { if (searchValue) {
const encodeText = encodeURI(searchValue); const encodeText = encodeURI(searchValue);
const reg = { condition.name = {
[Op.or]: [ [Op.or]: [
{ [Op.like]: `%${searchValue}%` }, { [Op.like]: `%${searchValue}%` },
{ [Op.like]: `%${encodeText}%` }, { [Op.like]: `%${encodeText}%` },
], ],
}; };
condition = {
...condition,
name: reg,
};
} }
try { try {
const result = await this.find(condition, sort); return await this.find(condition, sort);
return result as any;
} catch (error) { } catch (error) {
throw error; throw error;
} }