better default handling for request validation, move validationErrorMessage to options

This commit is contained in:
Christian Fehmer 2023-11-30 11:37:40 +01:00
parent b429400425
commit 3330221151
No known key found for this signature in database
GPG key ID: 7294582286D5F1F4
2 changed files with 43 additions and 27 deletions

View file

@ -46,21 +46,23 @@ router.post(
}),
authenticateRequest(),
RateLimit.newQuotesAdd,
validateRequest({
body: {
text: joi.string().min(60).required(),
source: joi.string().required(),
language: joi
.string()
.regex(/^[\w+]+$/)
.required(),
captcha: joi
.string()
.regex(/[\w-_]+/)
.required(),
validateRequest(
{
body: {
text: joi.string().min(60).required(),
source: joi.string().required(),
language: joi
.string()
.regex(/^[\w+]+$/)
.required(),
captcha: joi
.string()
.regex(/[\w-_]+/)
.required(),
},
},
validationErrorMessage: "Please fill all the fields",
}),
{ validationErrorMessage: "Please fill all the fields" }
),
asyncHandler(QuoteController.addQuote)
);
@ -68,14 +70,16 @@ router.post(
"/approve",
authenticateRequest(),
RateLimit.newQuotesAction,
validateRequest({
body: {
quoteId: joi.string().required(),
editText: joi.string().allow(null),
editSource: joi.string().allow(null),
validateRequest(
{
body: {
quoteId: joi.string().required(),
editText: joi.string().allow(null),
editSource: joi.string().allow(null),
},
},
validationErrorMessage: "Please fill all the fields",
}),
{ validationErrorMessage: "Please fill all the fields" }
),
checkIfUserIsQuoteMod,
asyncHandler(QuoteController.approveQuote)
);

View file

@ -129,24 +129,36 @@ interface ValidationSchema {
query?: object;
params?: object;
headers?: object;
validationErrorMessage?: string;
}
interface ValidationSchemaOption {
allowUnknown?: boolean;
}
interface ValidationSchemaErrorMessage {
validationErrorMessage?: string;
}
type ValidationSchemaOptions = {
[schema in keyof ValidationSchema]?: ValidationSchemaOption;
} & ValidationSchemaErrorMessage;
const VALIDATION_SCHEMA_DEFAULT_OPTIONS: ValidationSchemaOptions = {
body: { allowUnknown: false },
headers: { allowUnknown: true },
params: { allowUnknown: false },
query: { allowUnknown: false },
};
function validateRequest(
validationSchema: ValidationSchema,
options: ValidationSchemaOptions = {
body: { allowUnknown: false },
headers: { allowUnknown: true },
}
validationOptions: ValidationSchemaOptions = VALIDATION_SCHEMA_DEFAULT_OPTIONS
): RequestHandler {
const options = {
...VALIDATION_SCHEMA_DEFAULT_OPTIONS,
...validationOptions,
};
/**
* In dev environments, as an alternative to token authentication,
* you can pass the authentication middleware by having a user id in the body.
@ -159,7 +171,7 @@ function validateRequest(
};
}
const { validationErrorMessage } = validationSchema;
const { validationErrorMessage } = options;
const normalizedValidationSchema: ValidationSchema = _.omit(
validationSchema,
"validationErrorMessage"