npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@andrewcaires/sequelize

v3.2.1

Published

Decorators for sequelize

Readme

npm downloads size license

sequelize

TypeScript decorators for Sequelize v6. Declare models, columns, associations and hooks right on the class — no manual Model.init() or Model.hasMany/belongsTo.

Also includes:

  • Multi-connection support with schema replication.
  • Safe where / include / find parsers for API payloads.
  • Lightweight column sync via updateAttributes().

Installation

npm i @andrewcaires/sequelize

Requires TypeScript with experimentalDecorators and emitDecoratorMetadata enabled.

Links


Quick start

import { Column, Database, DefaultValue, Model, ModelName, Optional, Sequelize } from "@andrewcaires/sequelize";

export enum UserStatus {
  ACTIVE = "active",
  DISABLED = "disabled",
}

const sequelize = new Sequelize({
  uri: "mariadb://root:[email protected]:3306/sequelize",
});

@Database(sequelize)
@ModelName("user")
class UserModel extends Model<UserModel> {

  @Column.Id(7)
  declare readonly id: Optional<string>;

  @Column.String()
  declare name: Optional<string>;

  @Column.Enum(UserStatus)
  @DefaultValue(UserStatus.ACTIVE)
  declare status: UserStatus;

  @Column.CreatedAt()
  declare readonly created_at: Optional<Date>;

  @Column.UpdatedAt()
  declare readonly updated_at: Optional<Date>;

  @Column.DeletedAt()
  declare readonly deleted_at: Optional<Date | null>;
}

await sequelize.sync();

const user = await UserModel.create({ name: "John", status: UserStatus.ACTIVE });

Sequelize

Extends the native Sequelize and accepts all of its options, plus:

| option | type | description | |-------------|--------------------|---------------------------------------------------------------------| | id | string \| symbol | Instance id. Retrieve it later with Sequelize.getInstance(id). | | uri | string | Connection URI. Defaults to sqlite::memory:. | | prefix | string | Prefix prepended to modelName / tableName on sync(). | | timeout | string | Connection timeout (e.g. "10s", "2m"). Defaults to 10s. | | replicate | Sequelize | Another instance whose models should be cloned onto this one. |

Applied defaults: logging: false, define.timestamps: false, timezone: "+00:00".

Methods

  • sync(options?) — initializes every @Database model, resolves associations and calls the original sync.
  • addModel(model) — manually registers a model.
  • getModels() / getId() — introspection.
  • static getInstance(id) / getInstances() — access registered instances.
  • replicate(other) — clones the models from other onto this instance.

Model

Extends Sequelize's Model with a few helpers:

  • static getInstance<M>(id) — returns the ModelStatic bound to connection id.
  • static version() — reads the @Version metadata.
  • static updateAttributes() — diffs the current columns against the DB using QueryInterface (changeColumn / addColumn). Handy as a lightweight migration in development.

Class decorators

| decorator | description | |------------------------|--------------------------------------------------------------------| | @Database(seq) | Binds the model to a Sequelize instance (required). | | @ModelName(name) | Sets modelName (table name is pluralized). | | @TableName(name) | Sets tableName as-is. | | @Name(name, plural?) | Shortcut: trueModelName, falseTableName. | | @Underscored(flag?) | Enables underscored. | | @Indexes([...]) | Declares ModelIndexesOptions[]. | | @Scopes({...}) | Named scopes. | | @DefaultScope({...}) | Default scope. | | @Hooks({...}) | Registers multiple model hooks at once. | | @Version("1.0.0") | Tags the model version (exposed via Model.version()). |


Column decorators

All types live under the Column namespace (Column.<Type>()).

Data types

BigInt, Blob, Boolean, Char, DateOnly, Decimal, Double, Enum, Float, FullDate, Integer, Json, String(length?, binary?), Text, Time, Timestamp, UUIDV1, UUIDV4, UUIDV7.

Primary key

  • Column.Id() — auto-increment INTEGER.
  • Column.Id(1 | 4 | 7)UUID with UUIDV1 / UUIDV4 / UUIDV7 default.

Timestamps

  • Column.CreatedAt() / Column.UpdatedAt() — maps the property to createdAt / updatedAt.
  • Column.DeletedAt() — maps to deletedAt and enables paranoid: true automatically.

Modifiers

| decorator | effect | |--------------------|--------------------------------------| | @PrimaryKey | Marks the column as PK. | | @AutoIncrement | Marks as auto-increment. | | @AllowNull(bool) | Sets allowNull. | | @NotNull | Shortcut for allowNull: false. | | @Unique(bool) | Sets uniqueness. | | @DefaultValue(v) | Default value (literal or function). | | @Comment(str) | SQL comment. | | @Index2(opts?) | Column-level index. |


Association decorators

Always declared as @Association.<Kind>(() => OtherModel, opts?) — the arrow function avoids circular imports.

| decorator | maps to | |----------------------------------------------------|-----------------------------------------| | @Association.BelongsTo(() => M) | model.belongsTo(M) | | @Association.HasOne(() => M) | model.hasOne(M) | | @Association.HasMany(() => M) | model.hasMany(M) | | @Association.BelongsToMany(() => M, () => Thru) | model.belongsToMany(M, { through }) | | @Association.OneToOne(() => M) | hasOne + belongsTo | | @Association.OneToMany(() => M) | hasMany + belongsTo |

Defaults: foreignKey ← decorated property name, onDelete: "CASCADE", as ← target tableName (for BelongsTo). Through-table columns are stripped from query results automatically via a global beforeFind hook.


Method decorators (hooks)

@Database(sequelize)
@ModelName("user")
class UserModel extends Model<UserModel> {

  @Column.Id(7)
  declare readonly id: Optional<string>;

  @BeforeCreate()
  static hashPassword(user: UserModel) {
    // ...
  }
}

Use @Hook("beforeCreate") for custom hooks, or any of the shortcuts in decorators/method/hooks.


Multiple connections

const primary = new Sequelize({ id: "primary", uri: "mariadb://..." });
const replica = new Sequelize({ id: "replica", uri: "mariadb://...", replicate: primary });

await primary.sync();
await replica.sync();

const UserPrimary = UserModel.getInstance("primary");
const UserReplica = UserModel.getInstance("replica");

API-safe parsers

Helpers to validate filters coming from HTTP requests without exposing the full Sequelize surface.

Where

Converts JSON with friendly operators into Sequelize Op symbols, validated against an attribute allowlist.

import { Where } from "@andrewcaires/sequelize";

const { value, error } = Where.parse(
  ["name", "active"],
  JSON.stringify({ "$AND": [{ name: { "$LIKE": "%john%" } }, { active: true }] }),
);
// value → { [Op.and]: [{ name: { [Op.like]: "%john%" } }, { active: true }] }

Supported aliases: $OR/||, $AND/&&, $EQ/=/==, $NE/!=, $GT/>, $GTE/>=, $LT/<, $LTE/<=, $IS, $NOT, $BETWEEN, $NOTBETWEEN, $REGEXP, $NOTREGEXP, $IN, $NOTIN, $LIKE, $NOTLIKE, $STARTSWITH, $ENDSWITH, $SUBSTRING.

Find and Include

Find.parse(schema, text) validates a payload containing select, where, having, include, order, group, limit and offset, restricted to the attributes/associations declared in FindSchema / IncludeSchema. Designed for endpoints like GET /resource?q=....


License