Skip to content

Instantly share code, notes, and snippets.

@dfee
Created August 11, 2020 18:36
Show Gist options
  • Save dfee/7dd87864287c2d2376e8b492e00458cf to your computer and use it in GitHub Desktop.
Save dfee/7dd87864287c2d2376e8b492e00458cf to your computer and use it in GitHub Desktop.
type IsolationOptions = {
entityManager?: EntityManager<IDatabaseDriver<Connection>>;
flush?: boolean;
};
@Injectable()
export class UsersService {
constructor(
private readonly _entityManager: EntityManager<IDatabaseDriver<Connection>>,
) {}
public async create(
options: UserEntityOptions,
{
entityManager = this._entityManager,
flush = true,
}: IsolationOptions = {},
): Promise<UserEntity> {
const repo = this._getUserEntityRepository(entityManager);
const password = await bcrypt.hash(options.password, BCRYPT_ROUNDS);
const user = new UserEntity({ ...options, password });
repo.persist(user);
if (flush) {
await entityManager.flush();
}
return user;
}
private _getUserEntityRepository(
entityManager: EntityManager<IDatabaseDriver<Connection>> = this
._entityManager,
) {
return entityManager.getRepository(UserEntity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment