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

inversify-typeorm

v0.0.4

Published

Dependency injection and service container integration with TypeORM using InversifyJs library.

Downloads

124

Readme

Description

Dependency injection and service container integration with TypeOrm using InversifyJs library.

The implementation is strongly inspired by @nestjs/typeorm.

Usage

We assume that you are familiar with TypeOrm.

Install the required dependencies.

npm install --save inversify-typeorm

We need at least one entity, so we define the User entity firstly.

// user.entity.ts

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id!: number

  @Column()
  name!: string
}

To use Datasource and EntityManager, we need to bind them to the container using TypeOrmManager.importRoot(), and they will be available to inject across the entire project.

  • Note: To begin using the User entity, we need to let TypeORM know about it by inserting it into the entities array (unless you use a static glob path).
// app.ts

import { TypeOrmManager } from 'inversify-typeorm'
import { User } from './user.entity'

await TypeOrmManager.importRoot({
  type: 'mysql',
  host: 'localhost',
  port: 5432,
  username: 'test',
  password: 'test',
  database: 'test',
  synchronize: true,
  logging: false,
  entities: [User],
  migrations: [],
  subscribers: [],
})

TypeORM supports the repository design pattern, so each entity has its own repository. These repositories can be obtained from the database data source.

We can use TypeOrmManager.importRepository() to define which repositories are bound to the container. So the bound repositories will be also available to inject across the entire project.

// app.ts

await TypeOrmManager.importRepository([User])

Let's define the UserService to operate User entities.

Then we can inject the DataSource, EntityManager or UsersRepository into the UsersService:

  • inject DataSource using the @InjectDataSource()
  • inject EntityManager using the @InjectEntityManager()
  • inject UsersRepository using the @InjectRepository()

And the UserService also needed to be bounded to the container by @Service(), so that it can be created correctly by the container using the injected DataSource, EntityManager or UsersRepository.

// user.service.ts

import { DataSource, EntityManager, Repository } from 'typeorm'
import { InjectDataSource, InjectRepository, InjectEntityManager, Service } from 'inversify-typeorm'
import { User } from './user.entity'

@Service()
export class UserService {
  @InjectDataSource()
  private dataSource!: DataSource

  @InjectEntityManager()
  private entityManager!: EntityManager

  constructor(@InjectRepository(User) private repository: Repository<User>) {}

  saveByRepository(user: User): Promise<User> {
    return this.repository.save(user)
  }

  saveByManager(user: User): Promise<User> {
    return this.entityManager.save(user)
  }

  async saveManyByTransaction(users: User[]): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner()

    await queryRunner.connect()
    await queryRunner.startTransaction()
    try {
      for (const user of users) {
        await queryRunner.manager.save(user)
      }
      await queryRunner.commitTransaction()
    } catch (err) {
      await queryRunner.rollbackTransaction()
    } finally {
      await queryRunner.release()
    }
  }

  findAll(): Promise<User[]> {
    return this.repository.find()
  }
}

It's time to get the created UserService from the container by container.get<UserService>(UserService.name) and operate User entities!

// app.ts

import { contanier } from 'inversify-typeorm'

const userOne = new User()
userOne.id = 1
userOne.name = `Alice`

const userTwo = new User()
userTwo.id = 2
userTwo.name = `Bob`

const userThree = new User()
userThree.id = 3
userThree.name = `Olivia`

const userFour = new User()
userFour.id = 4
userFour.name = `Ada`

const service = container.get<UserService>(UserService.name)

/** Save through the various methods. */
await service.saveByRepository(userOne)
await service.saveByManager(userTwo)
await service.saveManyByTransaction([userThree, userFour])

/** Load the saved users so we can assert on them. */
const userList = await service.findAll()
console.log({ userList })

At last, we can close the connection with the database. Once connection is closed, we cannot use repositories or perform any operations except opening connection again.

// app.ts

try {
  await TypeOrmManager.destroyDataSource()
} cache (e) {
  // log error
}

Examples

All examples are available here.