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.
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.
- Transparent Execution: No need to manually drill or pass
EntityManageracross 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
tenantIdat runtime. - Auto-Inject Data: Automatically populate
tenantId,createdBy, etc. onINSERTandUPDATE. - 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.
npm install typeorm-policy
# or
yarn add typeorm-policy
# or
pnpm add typeorm-policyNote: This library relies on
reflect-metadataand experimental decorators. Ensure they are enabled in yourtsconfig.json.
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}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();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;
}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-policyautomatically interceptsqueryBuilder().insert()calls without the subscriber. The subscriber is only required for Object-level persists (repo.save()).
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);
});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();
});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();
});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();
}
}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();
}
}typeorm-policy intercepts query execution methods (getMany, getOne, execute, etc.) at the TypeORM SelectQueryBuilder prototype level.
- Request enters the
runInPolicyContextblock, storing context variables in anAsyncLocalStoragestate. - When a database query is invoked, the monkey-patch intercepts it.
- It resolves the entity being queried, checks the
AsyncLocalStoragefor policies attached via decorators. - Mutates the
expressionMapof theQueryBuilder(appends.andWhere()clauses). - Passes the modified QueryBuilder back to TypeORM for final SQL generation and execution.
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
This project is MIT licensed.