@httpc/kit
Version:
httpc toolbox for building function-based API with minimal code and end-to-end type safety
50 lines (49 loc) • 1.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Validate = exports.ValidationError = void 0;
const server_1 = require("@httpc/server");
const di_1 = require("../di");
const logging_1 = require("../logging");
const ValidationService_1 = require("./ValidationService");
class ValidationError extends server_1.BadRequestError {
constructor(errors) {
super("validation_error", errors);
this.errors = errors;
}
}
exports.ValidationError = ValidationError;
function Validate(...schemas) {
return async (call, next) => {
const logger = (0, logging_1.useLogger)();
if (schemas.length === 0) {
logger.warn("Validation skipped for call(%s): missing schema", call.path);
return await next(call);
}
const validator = (0, di_1.useInjected)(ValidationService_1.ValidationService);
// validate all call parameters
const params = call.params.map((param, idx) => {
const schema = schemas[idx];
if (!schema) {
logger.warn("Validation skipped for call(%s, argument#%d): missing schema", call.path, idx);
return param;
}
const result = validator.validate(param, schema);
if (!result.success) {
throw new ValidationError(result.errors);
}
return result.object;
});
// validate the rest of schemas with undefined if there's any
for (let idx = call.params.length; idx < schemas.length; idx++) {
const schema = schemas[idx];
if (!schema)
continue;
const result = validator.validate(undefined, schema);
if (!result.success) {
throw new ValidationError(result.errors);
}
}
return await next({ ...call, params });
};
}
exports.Validate = Validate;