Skip to content

Instantly share code, notes, and snippets.

@hungdev
Last active September 16, 2019 04:10
Show Gist options
  • Save hungdev/056d3599bd855b7fa978a9c909e7094d to your computer and use it in GitHub Desktop.
Save hungdev/056d3599bd855b7fa978a9c909e7094d to your computer and use it in GitHub Desktop.
validate in modal sequelize
// https://github.com/sequelize/sequelize/issues/2640
import { isUnique } from '../utils/validation';

module.exports = (sequelize, Sequelize) => {
  const TestCaseCategory = sequelize.define('test_case_categories', {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    // projectId: {
    //   type: Sequelize.STRING,
    // },
    name: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
      notEmpty: false,
      validate: {
        // unique: {
        //   args: true,
        //   msg: 'Name already in use!'
        // },
        notNull: {
          msg: 'Please enter test case category name',
        },
        notEmpty: {
          msg: 'Please enter test case category name',
        },
        len: {
          args: [3, 30],
          msg: 'Name must be between 3 and 30 characters in length',
        },
        isUnique: isUnique('TestCaseCategory', 'name'),
      },
    },
    code: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
      validate: {
        len: {
          args: [3, 30],
          msg: 'Name must be between 3 and 30 characters in length',
        },
        isUnique: isUnique('TestCaseCategory', 'code'),
      },
    },
    description: {
      type: Sequelize.STRING,
    },
  }, {
    updatedAt: 'updated_at',
    createdAt: 'created_at',
  });

  TestCaseCategory.associate = function (models) {
    models.TestCaseCategory.belongsTo(models.Project, { foreignKey: 'project_id' });
    models.TestCaseCategory.hasMany(models.TestCase, { foreignKey: 'category_id' });
    models.TestCaseCategory.hasMany(models.TestCaseCategoryField, { foreignKey: 'category_id' });
  };

  return TestCaseCategory;
};

=========
export function isUnique(modelName, field) {
  return function (value, next) {
    const m = require('../models');
    const query = {};
    query[field] = value;
    m[modelName].findOne({ where: query, attributes: ['id'] }).then((obj) => {
      if (obj) {
        next(`${field} "${value}" is already in use`);
      } else {
        next();
      }
    });
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment