-const UserSchema = mongoose.Schema({
- createdDate: {
- type: Date,
- default: Date.now
- },
- password: String,
- username: String,
- role: String
-})
-
-UserSchema.path('password').required(customUsersValidators.isUserPasswordValid)
-UserSchema.path('username').required(customUsersValidators.isUserUsernameValid)
-UserSchema.path('role').validate(customUsersValidators.isUserRoleValid)
-
-UserSchema.methods = {
- isPasswordMatch: isPasswordMatch,
- toFormatedJSON: toFormatedJSON
+module.exports = function (sequelize, DataTypes) {
+ const User = sequelize.define('User',
+ {
+ password: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ validate: {
+ passwordValid: function (value) {
+ const res = customUsersValidators.isUserPasswordValid(value)
+ if (res === false) throw new Error('Password not valid.')
+ }
+ }
+ },
+ username: {
+ type: DataTypes.STRING,
+ allowNull: false,
+ validate: {
+ usernameValid: function (value) {
+ const res = customUsersValidators.isUserUsernameValid(value)
+ if (res === false) throw new Error('Username not valid.')
+ }
+ }
+ },
+ role: {
+ type: DataTypes.ENUM(values(constants.USER_ROLES)),
+ allowNull: false
+ }
+ },
+ {
+ indexes: [
+ {
+ fields: [ 'username' ],
+ unique: true
+ }
+ ],
+ classMethods: {
+ associate,
+
+ countTotal,
+ getByUsername,
+ list,
+ listForApi,
+ loadById,
+ loadByUsername
+ },
+ instanceMethods: {
+ isPasswordMatch,
+ toFormatedJSON
+ },
+ hooks: {
+ beforeCreate: beforeCreateOrUpdate,
+ beforeUpdate: beforeCreateOrUpdate
+ }
+ }
+ )
+
+ return User