20. 模型中验证字段

2024-10-29  本文已影响0人  求墨者

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Article extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  Article.init({
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {
          msg: "标题不能为空类型"
        },
        notEmpty: {
          msg: "标题不能为空字符串"
        },
        len: {
          args: [2, 45],
          msg: "标题长度范围是2-45"
        }
      }
    },
    content: DataTypes.TEXT
  }, {
    sequelize,
    modelName: 'Article',
  });
  return Article;
};

router.post('/:id/delete', async function (req, res, next) {
  try {
    const { id } = req.params;

    const article = await Article.findByPk(id);

    if (article) {
      await article.destroy();

      res.json({
        status: true,
        message: "删除成功。"
      });
    } else {
      res.status(404).json({
        status: false,
        message: "删除失败。",
      });
    }

  } catch (error) {

    if (error.name == 'SequelizeValidationError') {
      res.status(400).json({
        errors: [error.message]
      })
    }else {
      res.status(500).json({
        errors: [error.message]
      })
    }
  }
});
上一篇 下一篇

猜你喜欢

热点阅读