UNPKG

@kitstack/nest-powertools

Version:

A comprehensive collection of NestJS powertools, decorators, and utilities to supercharge your backend development

55 lines 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SortFieldValidationGuard = SortFieldValidationGuard; const common_1 = require("@nestjs/common"); const typeorm_1 = require("typeorm"); function SortFieldValidationGuard(entity, allowedFields = [], defaultField = 'createdAt', options) { const orderByField = options?.orderByField || 'orderBy'; const orderDirField = options?.orderDirField || 'orderDir'; const baseAllowed = [ ...allowedFields, 'id', 'createdAt', 'updatedAt', 'deletedAt', 'created_at', 'updated_at', 'deleted_at', ]; class SortFieldValidationGuardClass { async canActivate(context) { const req = context.switchToHttp().getRequest(); const orderBy = (req.query[orderByField] || req.body?.[orderByField]); const validFields = [...baseAllowed]; if (entity && typeof entity === 'function') { try { const entCols = (0, typeorm_1.getMetadataArgsStorage)().columns.filter((col) => col.target === entity); validFields.push(...entCols.map((col) => col.propertyName)); } catch { } } if (orderBy) { if (!validFields.includes(orderBy)) { throw new common_1.BadRequestException(`Invalid ${orderByField} field. Allowed fields: ${validFields.join(', ')}`); } } else { if (req.query) req.query[orderByField] = defaultField; if (req.body && typeof req.body === 'object') req.body[orderByField] = defaultField; } const orderDir = (req.query[orderDirField] || req.body?.[orderDirField]); if (orderDir && !['ASC', 'DESC', 'asc', 'desc', 1, -1].includes(orderDir)) { throw new common_1.BadRequestException(`Invalid ${orderDirField} value. Allowed: ASC, DESC, asc, desc, 1, -1`); } return true; } } return (0, common_1.mixin)(SortFieldValidationGuardClass); } //# sourceMappingURL=order-by-field.guard.js.map