Created
May 30, 2019 15:15
-
-
Save jtushman/673f5cd9c0225ee50951fcf46be24df5 to your computer and use it in GitHub Desktop.
Best way to add helper methods on TypeORM models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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