编程语言
首页 > 编程语言> > 利用PostgreSQL来验证数据

利用PostgreSQL来验证数据

作者:互联网

使用Nest JS框架创建了一个小项目,按照TypeORM方法设计了数据模型,并构建了角色和用户表。User表中的roleId列是Role表的外键。此外,我让这email独一无二。

DB的ER图以及表格的主外键

屏幕截图:DB的ER图以及表格的主键和外键

一切都设置好了。现在,一切都是关于创建接受输入有效负载并将用户保留到数据库中的方法。

我的新手自己曾经写过像下面的代码,它曾经假设我需要实现什么,我需要自己做。

async saveUserV1(userSaveRequest: UserSaveRequest): Promise<string> {
    await this.validateRole(userSaveRequest.roleId);
    await this.validateEmail(userSaveRequest.email);

    const insertResult = await this.userRepository.insert({
        email: userSaveRequest.email,
        role: {
            id: userSaveRequest.roleId,
        },
    });

    return insertResult.generatedMaps[0].id;
}

private async validateRole(roleId: string): Promise<void> {
   const isRoleExist = await this.roleRepository.exist({ where: { id: roleId } });
   if (!isRoleExist) {
       throw new UnprocessableEntityException
(`Invalid role ID`);
   }
}


private async validateEmail(email: string): Promise<void> {
   const isUserWithEmailExist = await this.userRepository.exist({ where: { email: email } });
   if (isUserWithEmailExist) {
       throw new ConflictException(`Email is associated with another user`);
   }
}

让我们回顾一下代码。这是我的观察。

在SQL世界中,像PostgreSQL这样的数据库会自动处理验证。由于电子邮件字段中的唯一约束UQ_User_email和外键FK_User_roleId_Role_id强制执行的引用完整性,因此无需其他查询来验证数据。这些内置功能使额外的验证变得多余,并减少了对数据库的点击。

因此,作为拉取请求审查员,我现在的自己会将PR标记为请求更改,并建议将验证责任委托给数据库。

好的,我们需要重构代码。

我将利用数据库内置的错误处理能力。我的目标是处理异常,以便请求者将收到正确的错误消息。

这是我更改的代码。

async saveUserV2(userSaveRequest: UserSaveRequest): Promise<string> {
    try {
        const insertResult = await this.userRepository.insert({
            email: userSaveRequest.email,
            role: {
                id: userSaveRequest.roleId,
            },
        });
        return insertResult.generatedMaps[0].id;
    } catch (error) {
        this.handleRepositoryException(error);
        throw error;
    }
}

private handleRepositoryException(repositoryException: RepositoryException): void {
   const errorMap: Record<string, Error> = {
       UQ_User_email: new ConflictException(`Email is associated with another user`),
       FK_User_roleId_Role_id: new UnprocessableEntityException
(`Invalid role ID`),
   };
   throw errorMap[repositoryException.constraint];

标签:PostgreSQL,TypeORM
来源: