Reusable Query Patterns
Define where, select, relations, order, and pagination once. Apply anywhere with a simple API.
Define query patterns once, use everywhere. Clean, type-safe, and composable.
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();npm install typeorm-query-scopesyarn add typeorm-query-scopespnpm add typeorm-query-scopesDRY 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.
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.