Repositories

Factories are Creational objects that have a single purpose.

import { User } from './entities'
import { Repository, Connection } from 'typeorm'
import { CreateUserRequest } from './requests'

@injectable()
export class UserFactory {

  user: Repository<User>

  constructor (
    private connection: Connection // Injected
  ) {
    this.user = this.connection.getRepository(User)
  }

  /**
   * Creates a [User] using the data mapper pattern
   * - Ensures that the INSERT is wrapped in a transaction
   */
  async makeUser (data: CreateUserRequest): Promise<User> {
    return this.connection.transaction(async manager => {
      // Create the [User]
      const user = new User()
      user.firstName = data.firstName
      user.lastName = data.lastName
      user.email = data.email
      return manager.save(user)
    })
  }
}

(optional) But recommended we take the extra minute and bind the Factory to an interface to ensure TypeScript picks up any changes to our signature at a later date.

// file: users/interfaces.ts

interface IUserFactory {
  makeUser (data: CreateUserRequest): Promise<User>
}