28.用户接口为核心接口


对用户表新增字段

$ sequelize migration:create --name add-avatar-to-user
'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.addColumn('Users', 'avatar', {
      type: Sequelize.STRING
    })
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeColum('Users', 'avatar')
  }
};
$ sequelize db:migrate

最后记得在 User 模型中 添加 avatar 字段


种子数据

$ sequelize seed:generate --name user
    await queryInterface.bulkInsert('Users', [{
      email: 'admin@ims.com',
      username: 'admin',
      password: '123456',
      nickname: '管理员',
      sex: 2,
      role: 100,
      createdAt: new Date(),
      updatedAt: new Date()
    },
    {
      email: 'abc@ims.com',
      username: 'abc',
      password: '123456',
      nickname: '管理员',
      sex: 2,
      role: 0,
      createdAt: new Date(),
      updatedAt: new Date()
    }], {});
$ sequelize db:seed --seed ./seeders/20241029052732-user.js

自定义验证

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User 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
    }
  }
  User.init({
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: "必须填写" },
        notEmpty: { msg: "不能为空字符串" },
        isEmail: { msg: "格式不正确" },
        async isUnique(value) {
          const user = await User.findOne({ where: { email: value } })
          if (user) {
            throw new Error("邮箱已存在");
          }
        }
      }
    },
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    nickname: DataTypes.STRING,
    sex: DataTypes.TINYINT,
    company: DataTypes.STRING,
    introduce: DataTypes.TEXT,
    role: DataTypes.TINYINT,
    avatar: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容