|
| 1 | +import type { Error as MongooseError } from 'mongoose'; |
| 2 | +import type { Document } from 'mongoose'; |
| 3 | +import { ValidationError, ManyValidationError, ManyValidationsByIdx } from '../../errors'; |
| 4 | + |
| 5 | +export type ValidationErrorData = { |
| 6 | + path: string; |
| 7 | + message: string; |
| 8 | + value: any; |
| 9 | +}; |
| 10 | + |
| 11 | +export type ValidationsWithMessage = { |
| 12 | + message: string; |
| 13 | + errors: Array<ValidationErrorData>; |
| 14 | +}; |
| 15 | + |
| 16 | +export async function validateDoc(doc: Document): Promise<ValidationsWithMessage | null> { |
| 17 | + const validations: MongooseError.ValidationError | null = await new Promise((resolve) => { |
| 18 | + doc.validate(resolve); |
| 19 | + }); |
| 20 | + |
| 21 | + return validations?.errors |
| 22 | + ? { |
| 23 | + message: validations.message, |
| 24 | + errors: Object.keys(validations.errors).map((key) => { |
| 25 | + // transform object to array[{ path, message, value }, {}, ...] |
| 26 | + const { message, value } = validations.errors[key]; |
| 27 | + return { |
| 28 | + path: key, |
| 29 | + message, |
| 30 | + value, |
| 31 | + }; |
| 32 | + }), |
| 33 | + } |
| 34 | + : null; |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Make async validation for mongoose document. |
| 39 | + * And if it has validation errors then throw one Error with embedding all validation errors into it. |
| 40 | + */ |
| 41 | +export async function validateAndThrow(doc: Document): Promise<void> { |
| 42 | + const validations: ValidationsWithMessage | null = await validateDoc(doc); |
| 43 | + if (validations) { |
| 44 | + throw new ValidationError(validations); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Make async validation for array of mongoose documents. |
| 50 | + * And if they have validation errors then throw one Error with embedding |
| 51 | + * all validation errors for every document separately. |
| 52 | + * If document does not have error then in embedded errors' array will |
| 53 | + * be `null` at the same idx position. |
| 54 | + */ |
| 55 | +export async function validateManyAndThrow(docs: Document[]): Promise<void> { |
| 56 | + const manyValidations: ManyValidationsByIdx = []; |
| 57 | + let hasValidationError = false; |
| 58 | + |
| 59 | + for (const doc of docs) { |
| 60 | + const validations: ValidationsWithMessage | null = await validateDoc(doc); |
| 61 | + |
| 62 | + if (validations) { |
| 63 | + manyValidations.push(validations); |
| 64 | + hasValidationError = true; |
| 65 | + } else { |
| 66 | + manyValidations.push(null); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if (hasValidationError) { |
| 71 | + throw new ManyValidationError({ |
| 72 | + message: 'Some documents contain validation errors', |
| 73 | + errors: manyValidations, |
| 74 | + }); |
| 75 | + } |
| 76 | +} |
0 commit comments