@mbc-cqrs-serverless/import
Version:
55 lines • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseImportStrategy = void 0;
const common_1 = require("@nestjs/common");
const class_validator_1 = require("class-validator");
/**
* A base class (framework) that provides partial logic for an Import Strategy.
* Users can extend this class to save effort.
*/
class BaseImportStrategy {
async transform(input) {
return input;
}
async validate(data) {
const errors = await (0, class_validator_1.validate)(data);
if (errors.length > 0) {
const flatMessages = this.flattenValidationErrors(errors);
throw new common_1.BadRequestException({
statusCode: 400,
message: flatMessages,
error: 'Bad Request',
});
}
}
/**
* Recursively flattens validation errors into a single array of strings.
* @param errors The array of ValidationError objects.
* @param parentPath The path of the parent property, used for building nested paths.
* @returns An array of human-readable error strings.
*/
flattenValidationErrors(errors, parentPath = '') {
const messages = [];
for (const error of errors) {
const currentPath = parentPath
? `${parentPath}.${error.property}`
: error.property;
// If there are children, recurse to find the nested errors
if (error.children && error.children.length > 0) {
messages.push(...this.flattenValidationErrors(error.children, currentPath));
}
// Otherwise, we've found the constraint. Format the message.
else if (error.constraints) {
// The default message from class-validator often includes the property name.
// To avoid duplication like "attributes.policyType: policyType must be...",
// we can simply replace the first word of the message with the full path.
const firstConstraint = Object.values(error.constraints)[0];
const message = firstConstraint.replace(error.property, currentPath);
messages.push(message);
}
}
return messages;
}
}
exports.BaseImportStrategy = BaseImportStrategy;
//# sourceMappingURL=import-strategy.interface.js.map