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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hodfords/typeorm-helper

v8.0.0

Published

Typeorm Helper

Downloads

248

Readme

TYPEORM HELPER

Provide functions for relational handling in Typeorm.

How to use?

Extend BaseEntity from typeorm-helper

export class Post extends BaseEntity {
}

Extend BaseRepository from typeorm-helper

@EntityRepository(Post)
export class PostRepository extends BaseRepository<Post> {
}

RELATION LOADER

Single
let user = await User.createQueryBuilder().getOne();
await user.loadRelation(['posts', 'roles']);
Multiple
let users = await User.createQueryBuilder().find();
await users.loadRelation({
    'posts': (query) => {
        query.where(' orginationId != :orginationId ', { orginationId: 1 })
    }
});
Pagination
let userRepo = getConnection().getCustomRepository(UserRepository);
let userPagination = await userRepo.pagination({}, { page: 1, perPage: 10 });
await userPagination.loadRelation('posts');

Repository

@EntityRepository(Category)
export class CategoryRepository extends BaseRepository<Category> {
}

Entity

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

    @Column()
    name: string;

    @ManyToMany(() => Post, (post) => post.categories)
    posts: Post[];

    @OneToMany(() => PostCategory, postToCategory => postToCategory.category)
    public postCategories!: PostCategory[];
}

Relation condition

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

    @Column()
    name: string;

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

    @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(() => Post, (post) => post.user, { cascade: true })
    latestPost: Post;
}

Map data

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

    @Column()
    name: string;

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

WHERE EXPRESSION

For queries that are complex, need to be reused, or contain a lot of logic. We should use a class to store it.

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

    where(query: WhereExpression) {
        query.where({ userId: this.userId });
    }
}

Use:

this.postRepo.find({
    where: new BelongToUserWhereExpression(1)
})

Query Builder

For queries that are complex, need to be reused, or contain a lot of logic. We should use a class to store it.

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

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

    order(query: SelectQueryBuilder<Post>) {
        query.orderBy('id', 'DESC');
    }
}
this.postRepo.find(new PostOfUserQuery(1));

MIGRATIONS

We create a class, which wraps the migration of typeorm, allowing for simpler and more readable. For the update command, let's use pure queries for the time being.

  • Example:
export class CreateUserTable1626749239046 extends BaseMigration {
    async run(queryRunner: QueryRunner) {
        await this.create('User', (table) => {
            table.primaryUuid('id');
            table.string('email').index();
            table.string('firstName').nullable();
            table.string('lastName').nullable();
            table.string('password').nullable();
            table.integer('role');
            table.string('language').length(10).default("'en'");
            table.timestamp('lastLoginAt').nullable();
            table.uuid('enterpriseId').nullable().index().foreign('Enterprise');
            table.createdAt().index();
            table.updatedAt();
            table.deletedAt();
        });
    }

    async rollback(queryRunner: QueryRunner) {
        await this.drop('Fuel');
    }
}

Table method

    string(name: string, length?: number, options?: Partial<TableColumnOptions>): BaseColumn;
    strings(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    uuid(name?: string, options?: Partial<TableColumnOptions>): BaseColumn;
    uuids(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    primaryUuid(name?: string, options?: Partial<TableColumnOptions>): BaseColumn;
    integer(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    integers(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    timestamp(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    boolean(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    jsonb(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    json(name: string, options?: Partial<TableColumnOptions>): BaseColumn;
    decimal(name: string,precision: number = 10,scale: number = 2,options?: Partial<TableColumnOptions>): BaseColumn;
    baseTime(): void;
    createdAt(): BaseColumn;
    updatedAt(): BaseColumn;
    deletedAt(): BaseColumn;

Column method

    length(length: number): this;
    nullable(): this;
    unique(): this;
    index(): this;
    default(value: any): this;
    foreign(table: string, column?: string, onDelete?: string, onUpdate?: string): void;