In order to work with TypeORM and Postgress, three npm packages must be installed:
npm install @nestjs/typeorm typeorm pg --save
In order to set the uniqueness of a field in the entity:
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, Unique } from 'typeorm';
@Entity()
@Unique(['username'])
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}
Then in the user.repository.ts
:
import { ConflictException, InternalServerErrorException } from '@nestjs/common';
import { EntityRepository, Repository } from 'typeorm';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { User } from './user.entity';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void> {
const { username, password } = authCredentialsDto;
const user = new User();
user.username = username;
user.password = password;
try {
await user.save();
} catch (error) {
// duplicate username
if (error.code === '23505') {
throw new ConflictException('Username already exists');
} else {
throw new InternalServerErrorException();
}
}
}
}