Skip to content

TypeORM Query ScopesReusable Query Patterns for TypeORM

Define query patterns once, use everywhere. Clean, type-safe, and composable.

TypeORM Query Scopes

Quick Example

typescript
import { Scopes, DefaultScope, getScopedRepository } from 'typeorm-query-scopes';

@DefaultScope<User>({ where: { isActive: true } })
@Scopes<User, {
  verified: any;
  admin: any;
  withPosts: any;
}>({
  verified: { where: { isVerified: true } },
  admin: { where: { role: 'admin' } },
  withPosts: { relations: { posts: true } }
})
@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  email: string;

  @Column()
  role: string;

  @Column({ default: true })
  isActive: boolean;

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

// Usage
const userRepo = getScopedRepository(User, dataSource);

// Simple scope
const verified = await userRepo.scope('verified').find();

// Multiple scopes
const verifiedAdmins = await userRepo.scope('verified', 'admin').find();

// With relations
const usersWithPosts = await userRepo.scope('withPosts').find();

// Remove default scope
const allUsers = await userRepo.unscoped().find();

Installation

bash
npm install typeorm-query-scopes
bash
yarn add typeorm-query-scopes
bash
pnpm add typeorm-query-scopes

Why TypeORM Scopes?

DRY Principle

Stop repeating the same query patterns. Define once, use everywhere.

Better Maintenance

Change query logic in one place instead of hunting through dozens of files.

Type Safety

Get IDE autocomplete and compile-time validation for scope names.

What's Next?

Beta Release

This is version 1.0.0. The API is stable but may change based on community feedback. Please report any issues on GitHub!

Released under the MIT License.