Socket
Book a DemoInstallSign in
Socket

sequelize-qb

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sequelize-qb

Reusable query builder for Sequelize with caching and virtual attributes

1.0.1
latest
npmnpm
Version published
Weekly downloads
19
-84.8%
Maintainers
1
Weekly downloads
 
Created
Source

Sequelize QueryBuilder

A reusable query builder wrapper for Sequelize with:

  • Caching (Redis-based)
  • Virtual attributes (dynamic subqueries)
  • Filtering, sorting, pagination
  • Association inclusion
  • Automatic cache invalidation for read queries

🔹 Purpose

Sequelize QueryBuilder simplifies repetitive queries and boosts performance by:

  • Reducing duplicate query code
  • Adding virtual attributes (aggregates or subqueries) dynamically
  • Caching frequent read queries in Redis
  • Handling filters, sorting, pagination, and associations in a fluent API

⚡ When to Use

  • Your app has reusable read queries on models
  • You want Redis caching for performance
  • You want virtual attributes like totalViews or totalPosts
  • You frequently query related models and associations

❌ When to Avoid

  • Queries are highly dynamic and rarely reused (caching may not help)
  • For write-heavy workloads only (QueryBuilder primarily optimizes reads; write caching must be handled carefully)
  • When you need complex aggregations or raw SQL, QueryBuilder may not cover everything

📦 Installation

npm install sequelize-query-builder

⚙️ Initialization

QueryBuilder requires a Redis client to enable caching.

const { createClient } = require("redis");
const QueryBuilder = require("sequelize-query-builder");

const redis = createClient({ url: "redis://127.0.0.1:6379" });
await redis.connect();

// Initialize globally
QueryBuilder.init(redis);

🔹 Basic Usage

Import and create a QueryBuilder instance

const QueryBuilder = require("sequelize-query-builder");

// Assume User is a Sequelize model
const qb = new QueryBuilder(User);

1️⃣ Select columns (including virtual attributes)

const users = await qb
  .select(["id", "name", "totalViews"]) // totalViews is a virtual attribute
  .findAll();

2️⃣ Filtering

const activeUsers = await qb
  .filter({ status: "active" })
  .findAll();

3️⃣ Sorting

const sortedUsers = await qb
  .sort([["createdAt", "DESC"]])
  .findAll();

4️⃣ Pagination

const paginatedUsers = await qb
  .paginate({ page: 2, pageSize: 5 })
  .findAll();

5️⃣ Associations

const usersWithPosts = await qb
  .include([
    { model: Post, attributes: ["id", "title"] },
    { model: View, attributes: ["page"] }
  ])
  .findAll();

6️⃣ Caching

const cachedUsers = await qb
  .cache(60) // cache results for 60 seconds
  .findAll();

Cache uses namespace-based keys, automatically invalidated when QueryBuilder.invalidate() is called.

7️⃣ Cache Invalidation

// Invalidate cache for a model and related models
await QueryBuilder.invalidate("User", ["Post", "View"]);
  • Increments namespace version in Redis to automatically expire old cache entries
  • Useful after updates or deletions

🔹 Advanced Example

const qb = new QueryBuilder(User);

const users = await qb
  .select(["id", "name", "totalPosts", "totalViews"]) // virtual attributes
  .filter({ status: "active" })
  .include([{ model: Post, attributes: ["title"] }])
  .sort([["createdAt", "DESC"]])
  .paginate({ page: 1, pageSize: 10 })
  .cache(120) // 2 minutes
  .findAll();

console.log(users);

🔹 QueryBuilder Methods Compatibility

QueryBuilder MethodSequelize FeatureCompatibilityNotes
.select([...])attributes✅ FullyWorks with real and virtual attributes (via sequelize.literal).
.filter({...})where✅ FullySupports Sequelize operators (Op.gt, Op.or, etc.).
.include([...])include✅ FullySupports associations, nested includes, through, required.
.sort([...])order✅ FullyWorks with multiple columns and associations.
.paginate({ page, pageSize })limit + offset✅ FullySets limit and offset correctly.
.cache(ttl)n/a✅ FullyExternal Redis caching, does not modify Sequelize functionality.
.findAll(options)findAll✅ FullyRespects all QueryBuilder options, caching optional.
.findOne(options)findOne✅ FullyRespects all QueryBuilder options, caching optional.
.log(true/false)n/a✅ FullyOnly console logging, no effect on Sequelize.
.enableGlobalLogging(true/false)n/a✅ FullyGlobal console logging.
.invalidate(modelName, relatedModels)n/a✅ FullyInvalidates cached read queries for models and related models.
.create(data, options)create⚠️ PartialNot wrapped by default; must manually invalidate cache if used.
.update(values, options)update⚠️ PartialNot wrapped; call QueryBuilder.invalidate() after updates.
.destroy(options)destroy⚠️ PartialNot wrapped; call QueryBuilder.invalidate() after deletions.
.scope(...)Sequelize scopes⚠️ PartialCan pass via options to findAll, QueryBuilder does not automatically handle scopes.
.rawfindAll({ raw: true })⚠️ PartialWorks if passed manually; virtual attributes may need adjustment.
.aggregatecount, sum, max❌ Not supportedQueryBuilder focuses on findAll/findOne; aggregates must use Sequelize directly.

✅ Summary

  • Green ✅ → Fully supported, works out of the box
  • Yellow ⚠️ → Partially supported, manual adjustments needed
  • Red ❌ → Not supported, use Sequelize directly

⚠️ Notes & Tips

Virtual attributes: define in your model as:

User.virtualAttributes = (sequelize) => ({
  totalViews: sequelize.literal(`(SELECT COUNT(*) FROM Views v WHERE v.userId = User.id)`),
  totalPosts: sequelize.literal(`(SELECT COUNT(*) FROM Posts p WHERE p.userId = User.id)`)
});
  • Write operations (create, update, destroy) are not automatically cached. Call QueryBuilder.invalidate() after writes if needed.
  • Works with SQLite, MySQL, PostgreSQL. Make sure Sequelize is configured properly.
  • Logging can be enabled per query or globally:
QueryBuilder.enableGlobalLogging(true);
qb.log(true);

🔹 Summary

QueryBuilder makes Sequelize queries:

  • Reusable
  • Cached
  • Easy to maintain
  • Safe for read-heavy operations

📖 License

MIT License

Keywords

sequelize

FAQs

Package last updated on 25 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.