2023-08-01 21:01:49 +02:00
|
|
|
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
2023-04-27 23:18:48 +02:00
|
|
|
/* eslint-disable no-template-curly-in-string */
|
|
|
|
import * as yup from 'yup';
|
2023-08-25 00:08:34 +02:00
|
|
|
import { defaults } from 'lodash/fp';
|
2023-04-27 23:18:48 +02:00
|
|
|
import { YupValidationError } from './errors';
|
2020-02-14 11:42:03 +01:00
|
|
|
|
2023-08-25 00:08:34 +02:00
|
|
|
const handleYupError = (error: yup.ValidationError, errorMessage?: string) => {
|
2021-11-03 19:31:57 +01:00
|
|
|
throw new YupValidationError(error, errorMessage);
|
|
|
|
};
|
|
|
|
|
|
|
|
const defaultValidationParam = { strict: true, abortEarly: false };
|
|
|
|
|
2022-08-08 23:33:39 +02:00
|
|
|
const validateYupSchema =
|
2023-06-05 14:01:39 +02:00
|
|
|
(schema: yup.AnySchema, options = {}) =>
|
2023-08-25 00:08:34 +02:00
|
|
|
async (body: unknown, errorMessage?: string) => {
|
2022-08-08 23:33:39 +02:00
|
|
|
try {
|
|
|
|
const optionsWithDefaults = defaults(defaultValidationParam, options);
|
2023-04-28 18:20:31 +02:00
|
|
|
const result = await schema.validate(body, optionsWithDefaults);
|
|
|
|
return result;
|
2022-08-08 23:33:39 +02:00
|
|
|
} catch (e) {
|
2023-06-05 14:01:39 +02:00
|
|
|
if (e instanceof yup.ValidationError) {
|
|
|
|
handleYupError(e, errorMessage);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw e;
|
2022-08-08 23:33:39 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const validateYupSchemaSync =
|
2023-06-05 14:01:39 +02:00
|
|
|
(schema: yup.AnySchema, options = {}) =>
|
2023-08-25 00:08:34 +02:00
|
|
|
(body: unknown, errorMessage?: string) => {
|
2022-08-08 23:33:39 +02:00
|
|
|
try {
|
|
|
|
const optionsWithDefaults = defaults(defaultValidationParam, options);
|
|
|
|
return schema.validateSync(body, optionsWithDefaults);
|
|
|
|
} catch (e) {
|
2023-06-05 14:01:39 +02:00
|
|
|
if (e instanceof yup.ValidationError) {
|
|
|
|
handleYupError(e, errorMessage);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw e;
|
2022-08-08 23:33:39 +02:00
|
|
|
}
|
|
|
|
};
|
2021-10-27 18:54:58 +02:00
|
|
|
|
2023-08-25 00:08:34 +02:00
|
|
|
export { handleYupError, validateYupSchema, validateYupSchemaSync };
|