category.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. let randomColor = require('randomcolor')
  2. module.exports = (sequelize, DataTypes) => {
  3. let Category = sequelize.define('Category', {
  4. name: {
  5. type: DataTypes.STRING,
  6. unique: true,
  7. allowNull: false,
  8. validate: {
  9. notEmpty: {
  10. msg: 'The category name can\'t be empty'
  11. },
  12. isString (val) {
  13. if(typeof val !== 'string') {
  14. throw new sequelize.ValidationError('The category name must be a string')
  15. }
  16. }
  17. }
  18. },
  19. value: {
  20. type: DataTypes.STRING,
  21. unique: true
  22. },
  23. color: {
  24. type: DataTypes.STRING,
  25. defaultValue () {
  26. return randomColor({ luminosity: 'bright' })
  27. }
  28. }
  29. }, {
  30. hooks: {
  31. beforeCreate (category) {
  32. if(!category.name) {
  33. throw new sequelize.ValidationError('The category name cant\'t be empty')
  34. } else {
  35. let underscored = category.name.trim().replace(/\s/g, '_').toUpperCase()
  36. category.value = underscored
  37. }
  38. }
  39. },
  40. classMethods: {
  41. associate (models) {
  42. Category.hasMany(models.Thread)
  43. }
  44. }
  45. })
  46. return Category
  47. }