Skip to content

Hooks and validation ​

Lifecycle hooks and attribute / model validators work as in Sequelize v6. postgrelize adds validation with any Standard Schema library, such as zod, valibot or arktype.

Hooks ​

Register hooks in the model options (hooks), with the shorthand methods (Model.beforeCreate(fn)), or with addHook(type, [name], fn). A named hook can be removed later with removeHook(type, name).

ts
const audit: string[] = [];
const Member = sequelize.define(
  'Member',
  {
    email: { type: DataTypes.TEXT, allowNull: false },
    role: DataTypes.TEXT,
  },
  {
    hooks: {
      beforeValidate: (member: { email: string }) => {
        member.email = member.email.trim().toLowerCase();
      },
      afterCreate: (member: { get: (key: string) => unknown }) => {
        audit.push(`created ${String(member.get('email'))}`);
      },
    },
  },
);
Member.beforeCreate((member: { role: string | null }) => {
  member.role ??= 'member';
});
Member.addHook('beforeBulkDestroy', 'log-deletes', () => {
  audit.push('bulk destroy');
});

Hooks may be async; postgrelize awaits them in registration order. before* hooks may change the instance or the options object; throwing from a hook aborts the operation.

OperationHooks (in order)
create, save of a new recordbeforeValidate, afterValidate (or validationFailed), beforeCreate, afterCreate
save / update of an instancebeforeValidate, afterValidate (or validationFailed), beforeUpdate, afterUpdate
instance destroy / restorebeforeDestroy / afterDestroy, beforeRestore / afterRestore
upsertbeforeUpsert, afterUpsert
bulkCreate, Model.insertbeforeBulkCreate, afterBulkCreate
Model.update / destroy / restorebeforeBulkUpdate / afterBulkUpdate, beforeBulkDestroy / afterBulkDestroy, beforeBulkRestore / afterBulkRestore
findersbeforeFind, beforeFindAfterExpandIncludeAll, beforeFindAfterOptions, afterFind; beforeCount for count
connectingbeforeConnect (on the Sequelize instance; may change the connection config)

As in v6, beforeSave / afterSave hooks are registered as both create and update hooks, so they run in registration order together with beforeCreate / beforeUpdate. Bulk operations run per-row hooks only with individualHooks: true. Pass hooks: false to skip hooks for one call. An association defined with onDelete: 'CASCADE' and hooks: true destroys its associated rows one by one, with their beforeDestroy / afterDestroy hooks, when the owner instance is destroyed (as in v6); without hooks: true PostgreSQL cascades the delete and no hooks of the target run.

Sequelize-level hooks ​

Hooks can also be registered for every model: through the hooks constructor option, with sequelize.addHook(...), or as model defaults in define: { hooks }. Model hooks run first, then the Sequelize-level hooks:

ts
const sequelize = new Sequelize(url, {
  hooks: { beforeCreate: (instance) => audit('create', instance) },
});
sequelize.addHook('beforeConnect', async (config) => {
  config.password = await fetchDatabaseToken(); // e.g. short-lived IAM tokens
});

On the Sequelize instance every hook that runs also has a shorthand as in v6 (sequelize.beforeCreate(fn), sequelize.afterConnect('name', fn), sequelize.beforeBulkSync(fn), ...) next to addHook, removeHook, hasHook(s) and runHooks; models have Model.beforeSync(fn) / Model.afterSync(fn) besides the lifecycle shorthands. Hooks postgrelize never runs (beforeQuery, beforeAssociate, ...) have no shorthand. The class-level Sequelize.addHook, removeHook, hasHook(s), runHooks and the shorthands (Sequelize.beforeInit(fn), ...) exist as in v6; beforeInit(config, options) and afterInit(sequelize) run for every instance created afterwards (config and options may be changed before they are used), the other static hooks are only stored. sequelize.addHook('beforeDefine', (attributes, options) => ...) runs when a model is defined and may change the model name (options.modelName), options.name, the attributes and the options; afterDefine receives the model.

afterConnect runs once for every new pooled connection, after beforeConnect, with (connection, config) as in v6; connection is the pg client, so the hook can run session setup on it. If the hook throws, the connection is closed and the query that needed it rejects with that error.

ts
sequelize.addHook('afterConnect', async (connection) => {
  await connection.query("SET idle_in_transaction_session_timeout = '30s'");
});

All v6 hook names are accepted, but connection hooks other than beforeConnect and afterConnect and beforeQuery / afterQuery, beforeAssociate / afterAssociate are not run yet. beforeBulkSync / afterBulkSync run around sequelize.sync() and beforeSync / afterSync around each model's sync (also Model.sync()); hooks: false skips them.

Transactions in hooks ​

Hooks receive the options of the operation, including options.transaction. Pass it on to queries made inside the hook so they join the same transaction.

Validators ​

Attribute validators go into validate: the validator.js-based built-ins of v6 (isEmail, isUrl, len, min, max, isIn, notEmpty, is, not, ...) with optional { args, msg }, and custom functions that throw. An unknown validator name fails validation with Invalid validator function: <name> as a ValidationErrorItem, like v6. Model-level validators go into the validate model option and run with the instance as this:

ts
const Person = sequelize.define(
  'Person',
  {
    email: { type: DataTypes.TEXT, allowNull: false, validate: { isEmail: true } },
    name: {
      type: DataTypes.TEXT,
      validate: { len: { args: [2, 50], msg: 'name must be 2-50 characters' } },
    },
    age: {
      type: DataTypes.INTEGER,
      validate: {
        isAdult(value: unknown) {
          if (typeof value === 'number' && value < 18) {
            throw new Error('must be an adult');
          }
        },
      },
    },
  },
  {
    validate: {
      nameOrEmail(this: { name: string | null; email: string | null }) {
        if (this.name === null && this.email === null) {
          throw new Error('name or email is required');
        }
      },
    },
  },
);

Validation runs before create and save (skip it with validate: false) and on Model.update. bulkCreate and Model.insert validate only with validate: true. allowNull: false violations are reported as validation errors before the query runs; set a custom message with validate: { notNull: { msg } }.

Standard Schema postgrelize extension ​

Any Standard Schema v1 object can validate a single attribute (validate: { schema }) or the whole row (validationSchema model option). Schema issues become ValidationErrorItems with validatorKey: 'schema', and the issue path selects the attribute:

ts
const Signup = sequelize.define(
  'Signup',
  {
    email: { type: DataTypes.TEXT, allowNull: false, validate: { schema: z.email() } },
    age: { type: DataTypes.INTEGER, validate: { schema: z.number().int().min(0) } },
    role: DataTypes.TEXT,
  },
  {
    validationSchema: z
      .object({ age: z.number().nullish(), role: z.string().nullish() })
      .refine((row) => row.role !== 'admin' || (row.age ?? 0) >= 18, {
        message: 'admins must be adults',
        path: ['role'],
      }),
  },
);

The row schema receives all attribute values of the instance. postgrelize does not use the schema output: transformations (z.coerce, .transform) do not change the stored values. Use setters or hooks for that.

validationSchema is an extension. The model option schema keeps its v6 meaning (the PostgreSQL schema of the table).

Validation errors ​

A failed validation rejects with ValidationError, whose errors array holds one ValidationErrorItem per problem, with message, path (attribute), value, validatorKey and type:

ts
const error = await Signup.create({ email: 'nope', age: 12, role: 'admin' }).catch(
  (caught: unknown) => caught,
);
if (error instanceof ValidationError) {
  const paths = error.errors.map((item) => `${String(item.path)}:${String(item.validatorKey)}`);
  // paths: ['email:schema', 'role:schema']
  audit.push(...paths.toSorted());
}

Database constraint violations are reported separately, as UniqueConstraintError, ForeignKeyConstraintError or ExclusionConstraintError.

API reference ​

Released under the MIT License.