Factories

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 {

  constructor (
    private connection: Connection // Inject
  ) {}

  /**
   * - Creates a [User]
   * - Ensure 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 UserFactory to an IUserFactory implementaion to ensure TypeScript picks up any changes to our method signature at a later date.

// file: users/interfaces.ts

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