category.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. let randomColor = require('randomcolor')
  2. module.exports = (sequelize, DataTypes) => {
  3. let Category = sequelize.define('Category', {
  4. name: {
  5. type: DataTypes.STRING(191),
  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(191),
  21. unique: true
  22. },
  23. color: {
  24. type: DataTypes.STRING,
  25. defaultValue () {
  26. return randomColor({ luminosity: 'bright' })
  27. },
  28. validate: {
  29. isString (val) {
  30. if(typeof val !== 'string') {
  31. throw new sequelize.ValidationError('The color must be a string')
  32. }
  33. }
  34. }
  35. }
  36. }, {
  37. hooks: {
  38. beforeCreate (category) {
  39. if(!category.name) {
  40. throw new sequelize.ValidationError('The category name cant\'t be empty')
  41. } else {
  42. let underscored = category.name.trim().replace(/\s/g, '_').toUpperCase()
  43. category.value = underscored
  44. }
  45. }
  46. },
  47. classMethods: {
  48. associate (models) {
  49. Category.hasMany(models.Thread)
  50. }
  51. }
  52. })
  53. return Category
  54. }