Skip to content

About

Global Query Filters and Transparent Policy Injection for TypeORM via AsyncLocalStorage. Ideal for Multi-tenancy, Soft-deletes, and RBAC.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

1 Commit

Folders and files

Repository files navigation

typeorm-policy πŸ›‘οΈ

Global Query Filters and Transparent Policy Injection for TypeORM

NPM Version License TypeScript

typeorm-policy is a lightweight, high-performance extension for TypeORM inspired by Laravel Global Scopes and EF Core's HasQueryFilter.

It utilizes Node.js AsyncLocalStorage to automatically inject conditions (like tenant_id, user_id for soft-deletes, or ACL rules) into all your SELECT queries seamlessly, without requiring you to pass contexts or drill down EntityManager manually.

🌟 Why typeorm-policy?

When building multi-tenant applications or systems with complex Row-Level Security (RLS) / soft deletes, developers often forget to append .andWhere('tenantId = :id') in every single repository query. This library eliminates human error by enforcing conditions at the AST-level (SelectQueryBuilder expression map) right before SQL generation.

✨ Features

  • Transparent Execution: No need to manually drill or pass EntityManager across your architecture.
  • Global Query Filters: Automatically append conditions to operations (getMany, getOne, getRawMany, execute, etc.) across your entire application.
  • Multi-tenant Ready: Easily partition data by injecting tenantId at runtime.
  • Auto-Inject Data: Automatically populate tenantId, createdBy, etc. on INSERT and UPDATE.
  • Zero Configuration Boilerplate: Use simple class decorators (@Policy) to bind rules directly to your Entities.
  • Robust State Management: Powered by native Node.js AsyncLocalStorage (No memory leaks, minimal overhead).
  • Type-Safe: Written in TypeScript with full generic support.

πŸ“¦ Installation

npm install typeorm-policy
# or
yarn add typeorm-policy
# or
pnpm add typeorm-policy

Note: This library relies on reflect-metadata and experimental decorators. Ensure they are enabled in your tsconfig.json.

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

πŸš€ Quick Start

1. Initialize the Patcher

Before establishing your database connection, initialize the patcher. This hooks into TypeORM's SelectQueryBuilder safely.

import { initializePolicyContext } from 'typeorm-policy';

// Call this as early as possible in your application's bootstrap phase (e.g. main.ts / index.ts)
initializePolicyContext();

2. Define Policies on Entities

Attach global policies to your entities using the @Policy decorator. You can add as many policies as you need.

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { Policy } from 'typeorm-policy';

@Entity()
// 1. Simple condition-only syntax
@Policy('softDelete', (qb, context, alias) => {
  qb.andWhere(`${alias}.isDeleted = false`);
})
// 2. Full object syntax (Supports Auto-Inject on Insert/Update)
@Policy({
  name: 'tenant',
  condition: (qb, context, alias) => {
    // Applied on SELECT / UPDATE / DELETE
    qb.andWhere(`${alias}.tenantId = :tenantId`, { tenantId: context.tenantId });
  },
  onInsert: (entity, context) => {
    // Automatically applied on repository.save() or queryBuilder.insert()
    if (context?.tenantId) {
      entity.tenantId = context.tenantId;
    }
  },
})
export class Article {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column()
  tenantId: string;

  @Column({ default: false })
  isDeleted: boolean;
}

3. Register the PolicySubscriber (For save() Auto-Inject)

To enable automatic data injection (onInsert / onUpdate) when using repository.save(), add the PolicySubscriber to your TypeORM configuration.

import { PolicySubscriber } from 'typeorm-policy';
import { DataSource } from 'typeorm';

const dataSource = new DataSource({
  // ... your other config
  entities: [Article],
  subscribers: [PolicySubscriber], // Add this!
});

Note: typeorm-policy automatically intercepts queryBuilder().insert() calls without the subscriber. The subscriber is only required for Object-level persists (repo.save()).

4. Wrap Your Request with Context

Provide the context (e.g., tenantId, userId) around your application's request lifecycle. You can do this in an Express Middleware, a NestJS Interceptor, or a Fastify Hook.

Express Example:

import { runInPolicyContext } from 'typeorm-policy';
import express from 'express';

const app = express();

app.use((req, res, next) => {
  const context = {
    tenantId: req.headers['x-tenant-id'],
    userId: req.user?.id,
  };

  // All downstream TypeORM repository calls within `next()`
  // will automatically apply the 'tenant' and 'softDelete' policies.
  runInPolicyContext(context, next);
});

app.post('/articles', async (req, res) => {
  const article = new Article();
  article.title = 'Hello World';

  // `tenantId` is automatically injected into the DB based on context! No manual assignment needed.
  await articleRepository.save(article);
  res.json(article);
});

app.get('/articles', async (req, res) => {
  // Clean! No `where: { tenantId: ... }` needed.
  const articles = await articleRepository.find();
  res.json(articles);
});

πŸ› οΈ Advanced Usage

Bypassing Policies

For administrative tasks, you might want to bypass all policies (e.g., a Super Admin querying all tenants).

import { bypassPolicies } from 'typeorm-policy';

const allArticles = await bypassPolicies(async () => {
  // Returns everything! Bypasses both 'tenant' and 'softDelete' restrictions.
  return await articleRepo.find();
});

Disabling Specific Policies

Sometimes you want to disable a specific policy while keeping others intact.

import { disablePolicy } from 'typeorm-policy';

const includeDeleted = await disablePolicy('softDelete', async () => {
  // Ignores soft-delete, but the 'tenant' restriction still applies!
  return await articleRepo.find();
});

NestJS & Class-based Architecture (Method Decorators)

If you are using NestJS or prefer a class-based architecture, wrapping your methods in closures might not look elegant. For this, typeorm-policy provides highly ergonomic Method Decorators!

import { Controller, Get } from '@nestjs/common';
import { BypassPolicies, DisablePolicies, EnablePolicies } from 'typeorm-policy';

@Controller('articles')
export class ArticleController {
  constructor(private readonly articleService: ArticleService) {}

  @Get()
  @DisablePolicies('softDelete', 'tenant') // Automatically disables these policies for the entire method!
  async getAll() {
    // Both 'softDelete' and 'tenant' are disabled seamlessly
    return this.articleService.findAll();
  }

  @Get('/super-admin')
  @BypassPolicies() // Disables ALL policies for this execution block
  async getForSuperAdmin() {
    return this.articleService.findAll();
  }
}

Enabling Default-Disabled Policies

You can define a policy that is disabled by default, and only turn it on when explicitly needed.

// Third argument is `enabledByDefault` (set to false)
@Policy(
  'draftsOnly',
  (qb, context, alias) => {
    qb.andWhere(`${alias}.status = 'DRAFT'`);
  },
  false,
)
@Entity()
export class Post {
  /* ... */
}

// Usage via closure:
import { enablePolicy } from 'typeorm-policy';

const draftPosts = await enablePolicy('draftsOnly', async () => {
  return await postRepo.find();
});

// Or using NestJS Method Decorator:
import { EnablePolicies } from 'typeorm-policy';

@Controller('posts')
export class PostController {
  @Get('drafts')
  @EnablePolicies('draftsOnly') // Turns on the policy for this method
  async getDrafts() {
    return this.postService.findAll();
  }
}

πŸ”¬ How It Works

typeorm-policy intercepts query execution methods (getMany, getOne, execute, etc.) at the TypeORM SelectQueryBuilder prototype level.

  1. Request enters the runInPolicyContext block, storing context variables in an AsyncLocalStorage state.
  2. When a database query is invoked, the monkey-patch intercepts it.
  3. It resolves the entity being queried, checks the AsyncLocalStorage for policies attached via decorators.
  4. Mutates the expressionMap of the QueryBuilder (appends .andWhere() clauses).
  5. Passes the modified QueryBuilder back to TypeORM for final SQL generation and execution.

🀝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

πŸ“„ License

This project is MIT licensed.

About

Global Query Filters and Transparent Policy Injection for TypeORM via AsyncLocalStorage. Ideal for Multi-tenancy, Soft-deletes, and RBAC.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages