使用 TypeORM 使字段/列可选/必需

7 javascript node.js typeorm

我有这个成功写入 MySQL 的 cURL 命令:

curl -d '{"key1":"value", "key2":"value"}' -H "Content-Type: application/json" -X POST http://localhost:3010/customers
Run Code Online (Sandbox Code Playgroud)

此查询能够通过 TypeORM 库写入数据库,如下所示:

import {Customer} from "../entity/customer";
import {getRepository} from "typeorm";
const RCustomer = getRepository(Customer);

router.post('/', (req, res, next) => {
  return RCustomer.save(req.body).then(v => res.json({success: v}));
});
Run Code Online (Sandbox Code Playgroud)

这本不应该发生,因为“key1”和“key2”不是客户表中的字段!

客户模型如下所示:

'use strict';

import {Entity, PrimaryGeneratedColumn, Column, Index} from "typeorm";
import {MooveBaseEntity} from "./base";

@Entity()
@Index(["email"], { unique: true })
export class Customer extends MooveBaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  email: string;

  @Column()
  phonePrimary: string;

  @Column()
  phoneSecondary: string;

}
Run Code Online (Sandbox Code Playgroud)

所以我在想的是 - 我需要一种方法来使某些字段成为必需。理想情况下,默认情况下所有字段都是必需的,然后我可以做一些可选的(可为空的,或其他)。

我该怎么做呢?基本上,那个 cURL 命令应该永远不会成功。

Vad*_*imB 6

实际上,您可以使用第三方验证库,该库可用于在持久性发生之前验证您的模型: https: //github.com/typestack/class-validator

好处 - 您还可以使用注释来扩展当前模型并满足额外的验证要求。

因此,在调用“保存”操作之前,您可以执行验证并依赖验证结果过程或跳过保存操作。

import {validate} from "class-validator";
...

validate(customer).then(errors => { // errors is an array of validation errors
    if (errors.length > 0) {
        console.log("validation failed. errors: ", errors);
    } else {
        RCustomer.save(customer).then(v => res.json({success: v}));
    }
});
Run Code Online (Sandbox Code Playgroud)

其中所需的属性可以描述为:

@Entity()
@Index(["email"], { unique: true })
export class Customer extends MooveBaseEntity {

  @PrimaryGeneratedColumn()
  @IsDefined()
  id: number;

  @Column()
  @IsDefined()
  firstName: string;

  ...
}
Run Code Online (Sandbox Code Playgroud)


ple*_*ock 5

你有这样的行为,因为save它不关心你发送给它的对象中的属性,除了它需要的属性。在您的情况下,您没有发送 TypeORM 需要的任何属性,因此对于 typeorm,您的对象基本上是{}. save({})对您的情况有效,因为您不需要所有列。要使它们成为必需,您需要显式更改它们的可为空状态,例如:

 @Column({ nullable: false })
  firstName: string;
Run Code Online (Sandbox Code Playgroud)

  • `false` 是 `nullable` 的默认值 https://typeorm.io/#/decorator-reference/column-decorators (2认同)