Query Scopes

Reusable query filters for cleaner, more maintainable code

Define Scopes

models/user.tstypescript
import { defineModel, DataTypes } from "stabilize-orm";
const User = defineModel({
tableName: "users",
columns: {
id: { type: DataTypes.INTEGER },
email: { type: DataTypes.STRING, length: 100 },
isActive: { type: DataTypes.BOOLEAN },
role: { type: DataTypes.STRING, length: 50 },
},
scopes: {
active: (qb) => qb.where("isActive = ?", true),
admin: (qb) => qb.where("role = ?", "admin"),
byRole: (qb, role) => qb.where("role = ?", role),
},
});

Use Scopes

examples/use-scopes.tstypescript
const userRepo = stabilize.getRepository(User);
// Use a scope
const activeUsers = await userRepo
.scope("active")
.execute(stabilize.client);
// Chain multiple scopes
const activeAdmins = await userRepo
.scope("active")
.scope("admin")
.execute(stabilize.client);
// Scope with parameters
const editors = await userRepo
.scope("byRole", "editor")
.execute(stabilize.client);