-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (52 loc) · 1.76 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"use strict";
const { ValidationError, ValidationErrorItem } = require("sequelize");
const Joi = require("joi");
const sequelizeJoi = (sequelize) => {
if (!sequelize) {
throw new Error("The required sequelize instance option is missing");
}
sequelize.addHook("beforeValidate", (instance) => {
const changedKeys = Array.from(instance._changed);
if (!changedKeys.length) {
return;
}
const modelName = instance.constructor.name;
const validationErrors = [];
changedKeys.forEach((fieldName) => {
const fieldDefinition = instance.rawAttributes[fieldName];
if (!fieldDefinition || !fieldDefinition["schema"]) return;
const schema = fieldDefinition["schema"];
const value = instance[fieldName];
const validation = schema.validate(value, {
abortEarly: false,
allowUnknown: false,
noDefaults: false,
});
if (validation.error) {
validation.error.details.forEach((joiValidationError) => {
const errorMessageSegments = joiValidationError.message.split('"');
const errorPath = `${fieldName}.${joiValidationError.path.join(".")}`;
const errorMessage = `${modelName}.${errorPath}${errorMessageSegments[2]}`;
const errorType = "invalid schema";
const errorValue = joiValidationError.context.value;
const error = new ValidationErrorItem(
errorMessage,
errorType,
errorPath,
errorValue,
instance
);
validationErrors.push(error);
});
}
instance[fieldName] = validation.value;
});
if (validationErrors.length) {
throw new ValidationError(null, validationErrors);
}
});
};
module.exports = {
sequelizeJoi,
Joi,
};