我正在使用nestJS + typeorm + postgres数据库
我正在设置身份验证系统,并希望用户名和电子邮件具有唯一性。我想响应一个错误,如果用户为数据库输入了双重信息,则会发生这两种错误。对于一个唯一的列,这很容易,但是我有两个。
如果我尝试为用户名和电子邮件都插入重复符号,则我只会收到一个错误的用户名,因为它会跳过电子邮件:
我可以检查数据库中的现有条目,但是如果没有其他可能性,那将是一个或两个额外的数据库调用,这是我的最后一个计划。
我的实体:
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
@Unique('Dublicate name', ['name'])
username: string;
@Column()
@Unique('Dublicate email', ['email'])
email: string;
@Column()
password: string;
}
我的存储库:
@EntityRepository(User)
export class UserRepository extends Repository<User> {
async signUp(signUpCrendentialsDto: SignUpCrendentialsDto): Promise<void> {
const { username, password, email } = signUpCrendentialsDto;
const user = new User();
user.username = username;
user.password = password;
user.email = email;
try{
await user.save();
} catch (error) {
console.log(error);
}
}
}
错误:
[0] { QueryFailedError: doppelter Schlüsselwert verletzt Unique-Constraint »UQ_78a916df40e02a9deb1c4b75edb«
[0] at new QueryFailedError (E:\repositories\duckwars_backend\node_modules\typeorm\error\QueryFailedError.js:11:28)
[0] at Query.<anonymous> (E:\repositories\duckwars_backend\node_modules\typeorm\driver\postgres\PostgresQueryRunner.js:176:38)
[0] at Query.handleError (E:\repositories\duckwars_backend\node_modules\pg\lib\query.js:142:17)
[0] at Connection.connectedErrorMessageHandler (E:\repositories\duckwars_backend\node_modules\pg\lib\client.js:194:17)
[0] at Connection.emit (events.js:189:13)
[0] at Socket.<anonymous> (E:\repositories\duckwars_backend\node_modules\pg\lib\connection.js:126:12)
[0] at Socket.emit (events.js:189:13)
[0] at addChunk (_stream_readable.js:284:12)
[0] at readableAddChunk (_stream_readable.js:265:11)
[0] at Socket.Readable.push (_stream_readable.js:220:10)
[0] message:
[0] 'doppelter Schlüsselwert verletzt Unique-Constraint »UQ_78a916df40e02a9deb1c4b75edb«',
[0] name: 'QueryFailedError',
[0] length: 323,
[0] severity: 'FEHLER',
[0] code: '23505',
[0] detail: 'Schlüssel »(username)=(Nutzername)« existiert bereits.',
[0] hint: undefined,
[0] position: undefined,
[0] internalPosition: undefined,
[0] internalQuery: undefined,
[0] where: undefined,
[0] schema: 'public',
[0] table: 'user',
[0] column: undefined,
[0] dataType: undefined,
[0] constraint: 'UQ_78a916df40e02a9deb1c4b75edb',
[0] file:
[0] 'd:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\access\\nbtree\\nbtinsert.c',
[0] line: '534',
[0] routine: '_bt_check_unique',
[0] query:
[0] 'INSERT INTO "user"("username", "email", "password") VALUES ($1, $2, $3) RETURNING "id"',
[0] parameters: [ 'Nutzername', 'ich.kann@mich.reg', 'hAllo12345' ] }
在没有额外的数据库调用的情况下,有没有办法找到好的解决方案?