TypeORM extension which adds scope to entities.

Usage no npm install needed!

<script type="module">
  import typeormScope from 'https://cdn.skypack.dev/typeorm-scope';


TypeORM Scope

A query scope decorator for TypeORM entities. It patches TypeORM's SelectQueryBuilder so that it includes the scopes you define. This package was created to enable a simpler way of implementing a SoftDelete before an official solusion is implemented.


yarn add typeorm-scope
# or
npm install typeorm-scope --save



Before usage you need to patch TypeORM before calling any database method.

import { patchSelectQueryBuilder } from 'typeorm-scope'
const app = new Koa()


To define a scope for an entity you need to add the @Scope([...scopes]) decorator before the @Entity(). You can pass an array of query scopes to execute.

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
import { Scope } from "typeorm-scope"

@Scope<User>([(qb, alias) => qb.andWhere(`${alias}.deletedAt IS NULL`)])
export class User {
    id: number

    name: string

    deletedAt?: Date


There shouldn't be any changes in your services or repositories. You can use the EntityManager or any Repository or CustomRepository and the scopes will automatically be added to the resulting query. It will also work with queries created using the QueryBuilder. For example, the following snippet

getManager().find(User, { where: { name: Equal("OnePunchMan") } })

will produce an SQL query like

SELECT "User"."id" AS "User_id", "User"."name" AS "User_name" FROM "user" "User" WHERE "User"."name" = ? AND "User"."deletedAt" IS NULL
-- PARAMETERS: ["OnePunchMan"]

Disabling scopes

You are able to disable scopes by calling a helper function unscoped.

import { unscoped } from "typeorm-scope"

getManager().find(unscoped(connection, User), { where: { name: Equal("OnePunchMan") } })