sequelize-strict-attributes
sequelize-strict-attributes
is a plugin for Sequelize that adds stricter treatment of attribute access after specifying attributes in a query. This way, attempts to access instance attributes omitted from the query using attributes
will throw rather than silently failing by returning undefined. This is especially useful for scenarios where the column is expected to sometimes be null so a fallback value is provided for calculations.
Note: this is a runtime check. Types are included for the plugin itself, but the types of the returned instances will not be changed. To type checking, the instances will appear to still have omitted attributes.
Installation
npm install sequelize-strict-attributes
and include as a JavaScript or TypeScript module (types included):
import sequelizeStrictAttributes from 'sequelize-strict-attributes';
…or a CommonJS module:
const sequelizeStrictAttributes = require('sequelize-strict-attributes');
Supports the latest stable Sequelize, version 6.
Usage
Call the plugin with the active Sequelize instance immediately after it's instantiated.
const sequelize = new Sequelize(…);
sequelizeStrictAttributes(sequelize);
From this point on, any Model.findAll
or Model.findOne
query that specifies attributes:
—and does not use raw: true
—will throw if you try to access an attribute not included in the select list.
Example
For example, given a model that looks something like this:
const Cart = sequelize.define("Cart", {
subtotal: DataTypes.STRING,
tax: DataTypes.INTEGER,
});
And an instance fetched like this:
const cart = await Cart.findOne({
attributes: ["subtotal"],
});
When accessing the omitted attribute to determine if tax
needs to be calculated, the program will throw:
if (cart.tax === null) {
cart.tax = cart.subtotal * TAX_RATE;
}
if (cart.get("tax") === null) {
Includes
Included models will similarly be restricted if their attributes are specified on the include
.
const cart = await Cart.findOne({
attributes: [],
include: {
model: Customer,
attributes: ["name"],
},
});
await sendReceiptEmail({
name: cart.Customer.name,
email: cart.Customer.email,
});
Setting attributes
Setting the attribute directly or using Model::set
will still work. These changes can be saved as expected, though you won't be able to read them back on the same instance, even after a .reload()
. (Though shortcuts like addition–assignment will naturally throw.)
Motivation
Disallowing access of attributes that were excluded from a select is a common feature of other ORMs for good reason (eg Prisma excludes it from the returned type, ActiveRecord and Django throw errors on access). However, the Sequelize authors declined to support it in the core library. In lieu of core support, this plugin will help guard against the hazard.
Author
Alec Perkins
License
This package is licensed under the MIT License.
See ./LICENSE
for more information.