question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

beforeInsert not being triggered

See original GitHub issue

Pretty much what the title says, a method in a model decorated with @beforeInsert isn’t being triggered, causing a not-null constraint error to get triggered (that not null field should be getting populated by that beforeInsert method).

A repo with this issue can be found here: https://github.com/mogusbi/typedi-error

// user.model.ts

import {BeforeInsert, Column, Entity} from 'typeorm';
import {encryptionService} from '../../services/encryption';
import {BaseEntity} from '../base-entity';

@Entity()
export class User extends BaseEntity {
  @Column() public answer: string;
  @Column() public dob: Date;
  @Column({
    unique: true
  }) public emailAddress: string;
  @Column() public firstName: string;
  @Column() public password: string;
  @Column() public salt: string;
  @Column() public surname: string;
  @Column({
    unique: true
  }) public username: string;

  @BeforeInsert()
  public encrypt (): Promise<string> {
    return this.generateSalt()
      .then(
        () => this.hashAnswer()
      )
      .then(
        () => this.hashPassword()
      );
  }

  public generateSalt (): Promise<string> {
    return encryptionService
      .genSalt()
      .then(
        (salt: string) => this.salt = salt
      )
  }

  public hashAnswer (): Promise<string> {
    return encryptionService
      .hash(this.answer, this.salt)
      .then(
        (hash: string) => this.answer = hash
      );
  }

  public hashPassword (): Promise<string> {
    return encryptionService
      .hash(this.password, this.salt)
      .then(
        (hash: string) => this.password = hash
      );
  }
}
// user.controller.ts

import {Body, HttpCode, JsonController, Post} from 'routing-controllers';
import {IUser, User, UserService} from '../../entities/user';

@JsonController('/user')
export class UserController {
  constructor (
    private userService: UserService
  ) {}

  @Post()
  @HttpCode(201)
  public httpPost (
    @Body({
      required: true
    }) props: IUser
  ): Promise<User> {
    return this.userService.create(props);
  }
}

and an example POST request

{
	"answer": "Test",
	"dob": "1990-07-10T00:00:00+00:00",
	"emailAddress": "email@example.com",
	"firstName": "Mo",
	"password": "SuperSecurePassword",
	"surname": "Gusbi",
	"username": "mo.gusbi"
}

error being returned:

{
  "name": "error",
  "message": "null value in column \"salt\" violates not-null constraint",
  "stack": "error: null value in column \"salt\" violates not-null constraint\n    at Connection.parseE (/Users/mo/Repos/typedi-error/node_modules/pg/lib/connection.js:567:11)\n    at Connection.parseMessage (/Users/mo/Repos/typedi-error/node_modules/pg/lib/connection.js:391:17)\n    at Socket.<anonymous> (/Users/mo/Repos/typedi-error/node_modules/pg/lib/connection.js:129:22)\n    at emitOne (events.js:96:13)\n    at Socket.emit (events.js:188:7)\n    at readableAddChunk (_stream_readable.js:176:18)\n    at Socket.Readable.push (_stream_readable.js:134:10)\n    at TCP.onread (net.js:548:20)",
  "length": 334,
  "severity": "ERROR",
  "code": "23502",
  "detail": "Failing row contains (47a52ba1-369e-4733-94c0-74c624a5c839, 2017-07-16 19:50:20.3, 2017-07-16 19:50:20.3, 1, Test, 1991-01-25 00:00:00, me@mogusbi.co.uk, Mo, Password1!, null, Gusbi, mo.gusbi).",
  "schema": "public",
  "table": "user",
  "column": "salt",
  "file": "execMain.c",
  "line": "1732",
  "routine": "ExecConstraints"
}

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:8
  • Comments:13 (2 by maintainers)

github_iconTop GitHub Comments

52reactions
rationalthinker1commented, Mar 20, 2019

You have to instantiate the Entity and assign the attributes to it and then save.

async create(attributes: DeepPartial<T>) {
    const entity = Object.assign(new User(), attributes);
    return this.repository.save(entity);
}
12reactions
mmiszycommented, Oct 18, 2017

@mogusbi I think this is definitely a bug, but there’s a simple workaround. The problem is that you’re calling persist on an object literal like you do here in src/entities/user/user.service.ts#L14

return this.repository.persist(props);

Instead, create a model instance first and call persist on the instance:

const instance = this.repository.create(props);
return this.repository.persist(instance);

The bug occurs because of how listener.isAllowed method is implemented – it uses instanceof operator and thus doesn’t work with object literals.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Before Insert not working or triggered at all #5530
Neither AfterInsert nor BeforeInsert were trigger, but calling .create() first solved it. Docs over at https://typeorm.io/#/listeners-and- ...
Read more >
BeforeInsert and AfterInsert hook not being called
I have a BeforeInsert and AfterInsert hook that is not being called. All it does is log hook . I am using nestjs-graphql....
Read more >
Before insert trigger not working
Before insert trigger not working. I need custom picklist fields on Account to be autopopulated on creating New Account.
Read more >
Before insert is not taking effect
I'm trying to update an Email field on an sObject, we have lots of relationships, so using workflow rule is out of the...
Read more >
MySQL BEFORE INSERT Trigger Explained by Practical ...
MySQL BEFORE INSERT triggers are automatically fired before an insert event occurs on the table. The following illustrates the basic syntax of creating...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found