Skip to content

Instantly share code, notes, and snippets.

@jtushman
Created May 30, 2019 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtushman/673f5cd9c0225ee50951fcf46be24df5 to your computer and use it in GitHub Desktop.
Save jtushman/673f5cd9c0225ee50951fcf46be24df5 to your computer and use it in GitHub Desktop.
Best way to add helper methods on TypeORM models
import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToMany,
BeforeInsert,
OneToOne,
Connection
} from 'typeorm';
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('varchar', { length: 255, unique: true })
email: string;
@Column('text', { nullable: true })
password: string;
async setPassword(connection: Connection, unencodedPassword: string): Promise<User> {
const userRepo = connection.getRepository(User);
this.password = await encrpytPassword(unencodedPassword);
this.passwordSetOn = new Date();
return userRepo.save(this);
}
}
// then to use:
User user = connection.getRepository(User).findOneOrFail({id: userId})
user.setPassword(connection, 'secretPassword')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment