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;
  withScopedRole: any;
}>({
  verified: { where: { isVerified: true } },
  admin: { where: { role: 'admin' } },
  withPosts: { relations: { posts: true } },
  withScopedRole: {
    relations: { role: true },
    relationScopes: {
      role: ['activeOnly', 'adminOnly']
    }
  }
})
@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();

// Relations with related-entity scopes
const usersWithScopedRole = await userRepo.scope('withScopedRole').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?

Latest Release

This is version 1.0.3 with typed object-based select support and nested relation scope select merging. You can now select fields with Prisma-style object trees while keeping relation scopes type-safe.

Released under the MIT License.