乐闻世界logo
搜索文章和话题

How to add a custom DataType in Sequelize ORM

1个答案

1

Adding custom data types in Sequelize ORM is an advanced topic typically used when projects require handling special data formats. For instance, if you need to handle extremely large or extremely small numbers that existing data types cannot accommodate, you may need to create a custom data type. Here are the steps to add custom data types in Sequelize:

Step 1: Understanding Sequelize's DataType Abstraction

In Sequelize, all data types are instances of the DataType class. These include STRING, INTEGER, BIGINT, etc. To create a custom data type, you first need to understand how Sequelize defines these standard data types.

Step 2: Defining a Custom DataType Class

You can create a custom data type by extending Sequelize's ABSTRACT class. For example, if you want to handle numbers within a specific range, you might implement it as follows:

javascript
const { DataTypes } = require('sequelize'); class RANGED_NUMBER extends DataTypes.ABSTRACT { constructor(min, max) { super(); this.min = min; this.max = max; } toSql() { return 'INTEGER'; } _stringify(value) { return this._sanitize(value).toString(); } _sanitize(value) { if (value < this.min || value > this.max) { throw new Error(`Value ${value} is out of range (${this.min} to ${this.max})`); } return value; } }

Step 3: Using Custom DataType in Models

Once defined, you can use your custom data type in Sequelize models just like any other data type:

javascript
const { Sequelize } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const Model = sequelize.define('Model', { limitedNumber: { type: new RANGED_NUMBER(10, 100), allowNull: false } });

Step 4: Performing Data Validation

Before saving data to the database, Sequelize invokes the methods of your custom data type to process and validate the data. In the example above, attempting to save a value outside the 10–100 range will trigger an error from the _sanitize method.

Conclusion

By following these steps, you can add custom data types with specific rules and behaviors to Sequelize, enhancing data processing flexibility and security. This approach is particularly useful for handling unique project requirements or strengthening data validation.

2024年6月29日 12:07 回复

你的答案