简体   繁体   中英

How to do Prisma runtime model validation?

In my application, I have validated the input credential at the DTO level by using class-validator. But I need runtime model validation like sequelize ORM.

In sequelize:

'use strict';
import { DataTypes, Sequelize } from 'sequelize';

function User(sequelize: Sequelize) {
  const user = sequelize.define(
    'User',
    {
      name: {
        type: DataTypes.STRING,
        allowNull: false
      },
      role: {
        type: DataTypes.STRING(20),
        allowNull: false
      },
      email: {
        type: new DataTypes.STRING,
        allowNull: false,
        validate: {
          isEmail: {
            // args: true,
            msg: 'Invalid email'
          },
          len: {
            args: [1, 100] as readonly [number, number],
            msg: 'Email length should be 1 to 100 characters'
          },
          notNull: {
            // args: true,
            msg: 'Email cannot be empty'
          }
        }
      },
      password: {
        type: DataTypes.VIRTUAL,
        allowNull: true,
      },
    },
    {
      tableName: 'users',
      underscored: true,
      createdAt: 'created_at',
      updatedAt: 'updated_at',
      deletedAt: 'deleted_at',
      paranoid: true
    }
  );

  return user;
}
export default User;

Is there any possibility to do model validation in Prisma?

There is an open feature request for Prisma to support runtime model validation directly at the Schema level. Alternatively, you can leverage the Client Extensions to perform validation. There is an example in this blog post that shows how to perform custom runtime validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM