【发布时间】:2021-10-06 16:57:23
【问题描述】:
我有一个 NestJS 项目,它有一个名为 Users 的实体。在这个实体中,有关于用户的登录相关信息。我还有另一个名为 Profile 的实体,它将保存用户的姓名、图片等...
这两个实体相互关联,问题是,当用户注册时,我还没有任何个人资料信息。如何在 TypeOrm 上实现这一点?我尝试只保存用户信息,但是当我创建配置文件时,它与用户无关。
谢谢
这是我的实体:
用户实体
import {
BaseEntity,
Column,
Entity,
JoinColumn,
OneToOne,
PrimaryGeneratedColumn,
Unique,
} from 'typeorm';
import * as bcrypt from 'bcrypt';
import { UserProfile } from './profile/user-profile.entity';
@Entity()
@Unique(['email'])
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
email: string;
@Column()
password: string;
@Column()
salt: string;
async validatePassword(password: string): Promise<boolean> {
const hash = await bcrypt.hash(password, this.salt);
return hash === this.password;
}
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
registration_date: Date;
@Column({ nullable: true })
login_method: string;
@Column()
role: string;
@OneToOne(() => UserProfile, (profile) => profile.user)
@JoinColumn()
profile: UserProfile;
}
用户存储库(保存方法)
async newUser(authCred: AuthCredentialsDTO): Promise<User> {
const { password } = authCred;
const userCred = new User();
Object.assign(userCred, authCred);
userCred.salt = await bcrypt.genSalt();
userCred.password = await this.hashPassword(password, userCred.salt);
try {
await userCred.save();
return userCred;
} catch (error) {
throw new InternalServerErrorException(error);
}
}
个人资料实体
import { BaseEntity, Column, Entity, OneToOne, PrimaryGeneratedColumn } from 'typeorm';
import { User } from '../user.entity';
@Entity()
export class UserProfile extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ nullable: true })
firstName: string;
@Column({ nullable: true })
lastName: string;
@Column({ nullable: true })
address: string;
@Column({ nullable: true })
address_comp: string;
@Column({ nullable: true })
city: string;
@Column({ nullable: true })
province_state: string;
@Column({ nullable: true })
postal_code: string;
@Column({ nullable: true })
picture: string;
@OneToOne(() => User, (user) => user.profile)
user: User;
}
【问题讨论】:
标签: mysql postgresql nestjs typeorm