npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hodfords/typeorm-helper

v11.1.5

Published

Simplifies TypeORM usage in NestJS apps

Downloads

671

Readme

Installation 🤖

Install the typeorm-helper package with:

npm install @hodfords/typeorm-helper --save

Usage 🚀

Defining custom repositories and entities

When managing different entities, you can define custom repositories and entities. Below is an example for the Category entity and its corresponding repository.

Entity

The Category table in the database is modeled by the CategoryEntity, typeorm decorators should be used to define this entity.

import { BaseEntity } from '@hodfords/typeorm-helper';
import { Column, Entity, ManyToMany, JoinTable, PrimaryGeneratedColumn } from 'typeorm';

@Entity('Category')
export class CategoryEntity extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(() => PostEntity, (post) => post.categories)
    @JoinTable({ name: 'PostCategory' })
    posts: PostEntity[];
}

Repository

The CategoryRepository is a custom repository that handles all database operations related to the CategoryEntity. By using the @CustomRepository decorator and extending BaseRepository, you ensure that your repository has both common CRUD functionality and can be easily customized with entity-specific methods.

import { CustomRepository, BaseRepository } from '@hodfords/typeorm-helper';

@CustomRepository(CategoryEntity)
export class CategoryRepository extends BaseRepository<CategoryEntity> {}

Lazy Relations

Lazy relations allow you to load related entities only when they are needed. This can significantly improve performance by preventing the fetching of unnecessary data upfront.

This functionality supports handling single entity, collection of entities, and paginated collection. Below is an example of how to load a list of posts associated with a specific category.

Single entity
const categoryRepo = getDataSource().getCustomRepository(CategoryRepository);
const category = await categoryRepo.findOne({});
await category.loadRelation(['posts']);
Collection of entities
const categoryRepo = getDataSource().getCustomRepository(CategoryRepository);
const categories = await categoryRepo.findOne({ name: ILIKE('%football' });
await this.categories.loadRelations(['posts']);
Paginate collection
const categoryRepo = getDataSource().getCustomRepository(CategoryRepository);
const pagedCategories = await categoryRepo.pagination({}, { page: 1, perPage: 10 });
await pagedCategories.loadRelation('posts');

You can also make use of the loadRelations function to efficiently load and retrieve related data

await loadRelations(categories, ['posts']);

Relation Condition

Sometimes, you need to add custom conditions when loading related entities. typeorm-helper provides the @RelationCondition decorator for this purpose.

Simple condition

This ensures that the posts relation is only loaded when the condition posts.id = :postId is satisfied.

@Entity('User')
export class UserEntity extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @RelationCondition((query: SelectQueryBuilder<any>) => {
        query.where(' posts.id = :postId', { postId: 1 });
    })
    @OneToMany(() => PostEntity, (post) => post.user, { cascade: true })
    posts: PostEntity[];

    @RelationCondition((query: SelectQueryBuilder<any>, entities) => {
        query.orderBy('id', 'DESC');
        if (entities.length === 1) {
            query.limit(1);
        } else {
            query.andWhere(
                ' "latestPost".id in (select max(id) from "post" "maxPost" where "maxPost"."userId" = "latestPost"."userId")'
            );
        }
    })
    @OneToOne(() => PostEntity, (post) => post.user, { cascade: true })
    latestPost: PostEntity;
}

Complex condition

Here, the condition applies a limit if only one entity is found, and fetches the latest post for each user if there are multiple entities.

@Entity('User')
export class UserEntity extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @RelationCondition(
        (query: SelectQueryBuilder<any>) => {
            query.where(' posts.id = :postId', { postId: 1 });
        },
        (entity, result, column) => {
            return entity.id !== 2;
        }
    )
    @OneToMany(() => PostEntity, (post) => post.user, { cascade: true })
    posts: PostEntity[];
}

Where Expression

For complex queries that need to be reused or involve a lot of logic, it's best to put them in a class

export class BelongToUserWhereExpression extends BaseWhereExpression {
    constructor(private userId: number) {
        super();
    }

    where(query: WhereExpression) {
        query.where({ userId: this.userId });
    }
}
const posts = await this.postRepo.find({ where: new BelongToUserWhereExpression(1) });

Query Builder

For complex and reusable queries, it's helpful to put the logic inside a class. This makes it easier to manage and reuse the query, resulting in cleaner and more maintainable code.

export class PostOfUserQuery extends BaseQuery<PostEntity> {
    constructor(private userId: number) {
        super();
    }

    query(query: SelectQueryBuilder<PostEntity>) {
        query.where({ userId: this.userId }).limit(10);
    }

    order(query: SelectQueryBuilder<PostEntity>) {
        query.orderBy('id', 'DESC');
    }
}
const posts = await this.postRepo.find(new PostOfUserQuery(1));

License 📝

This project is licensed under the MIT License