Making fields/columns optional/required using TypeORM

user7898461 picture user7898461 · Jul 2, 2018 · Viewed 8.2k times · Source

I have this cURL command that successfully wrote to MySQL:

curl -d '{"key1":"value", "key2":"value"}' -H "Content-Type: application/json" -X POST http://localhost:3010/customers

This query was able to write to the db through via the TypeORM library, like so:

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}));
});

that never should have happened since "key1" and "key2" aren't fields in the customers table!

the customers model looks like:

'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;

}

so what I am thinking is - I need a way to make certain fields required. Ideally all fields would be required by default, and then I could make some optional (nullable, or whatever).

How do I do this? Basically, that cURL command should never have succeeded.

Answer

pleerock picture pleerock · Jul 2, 2018

You have such behaviour because save does not care about properties in the object you sent to it except for the properties it needs. In your case you did not sent any properties TypeORM needs, so for typeorm your object is basically {}. save({}) is valid in your case since all columns in your aren't required. To make them required you need to explicitly change their nullable state, e.g.:

 @Column({ nullable: false })
  firstName: string;