-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperience.js
111 lines (102 loc) · 2.39 KB
/
experience.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
module.exports = function (sequelize, DataTypes) {
let Experience = sequelize.define("Experience", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [3, 50],
msg: "Experience name must have at least 3 and max 20 characters"
}
}
},
location: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [6, 200],
msg: "Location must have at least 6 and max 200 characters"
}
}
},
location2: {
type: DataTypes.STRING,
allowNull: true
},
location3: {
type: DataTypes.STRING,
allowNull: true
},
description: {
type: DataTypes.TEXT,
allowNull: false,
validate: {
len: {
args: [10, 1000],
msg: "Experience description must have at least 10 and max 1000 characters"
}
}
},
image: {
type: DataTypes.STRING,
allowNull: true
}
},
{
freezeTableName: true,
hooks: {
//trigger to update the file name and user score after store on database
afterCreate: function (experience) {
if (experience.image) {
let fileName = "experience_" + experience.id + "." + experience.image;
experience.image = fileName;
Experience.update({
image: fileName
},
{
where: {
id: experience.id
}
}).then(() => {
console.log("Image renamed!");
});
}
//update the user score
this.sequelize.models.User.update({
score: sequelize.literal("score + 5")
},
{
where: { id: experience.UserId }
}).then(() => {
console.log("User score was updated!");
});
}
}
});
Experience.associate = function (models) {
Experience.hasMany(models.Review, {
foreignKey: {
allowNull: false
}
});
Experience.belongsTo(models.User, {
foreignKey: {
allowNull: false
}
});
Experience.belongsTo(models.Category, {
onDelete: "CASCADE",
foreignKey: {
allowNull: false,
validate: {
notNull: {
args: true,
msg: "You must select a category"
}
}
}
});
};
return Experience;
};