Skip to content

Skip constructor when entity is loaded from database #1772

Closed

Description

@pepakriz

Issue type:

[ ] question
[x] bug report
[x] feature request
[ ] documentation issue

Database system/driver:

[x] cordova
[x] mongodb
[x] mssql
[x] mysql / mariadb
[x] oracle
[x] postgres
[x] sqlite
[x] sqljs
[x] websql

TypeORM version:

[x] latest
[ ] @next
[ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

Create some entity with non-empty constructor. For example:

@Entity()
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    private title: string;

    constructor(title: string) {
        if (title === undefined) {
            throw new Error("Invalid title value");
        }

        this.title = title;
    }

}

When entity is loaded from db, Invalid title value is thrown, because constructor is invoked without args. I think calling constructor must be skipped somehow in this case.

Activity

  1. lodemo commented on Mar 29, 2018

    @lodemo

    I think just checking the value instead of throwing an error would be a straightforward solution while maintaining the current functionality.

    @Entity()
    export class Post {
    
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        private title: string;
    
        constructor(title?: string) {
            if (title !== undefined) {
                this.title = title;
            }
        }
    
    }
  2. pepakriz commented on Mar 29, 2018

    @pepakriz
    ContributorAuthor

    @lodemo I've already tried your solution, but It leads to error: error TS2564: Property 'title' has no initializer and is not definitely assigned in the constructor.

  3. lodemo commented on Mar 29, 2018

    @lodemo

    This is probably due to the strictPropertyInitialization compile flag, this could help.

    You could assign title to a default value if not given, or use the definite assignment assertion modifier(!) like this.

    @Entity()
    export class Post {
    
        @PrimaryGeneratedColumn()
        id: number;
    
        @Column()
        private title!: string;
    
        constructor(title?: string) {
            if (title !== undefined) {
                this.title = title;
            }
        }
    
    }
  4. pleerock commented on Mar 29, 2018

    @pleerock
    Member

    Correct, you should understand what each compile option will bring it, value of it and how you are going to use it. You either need to use @lodemo solution either initialize your property in the constructor.

    I'll close this issue since its not related to TypeORM and more related to language itself. Feel free to keep discussion.

  5. pepakriz commented on Mar 29, 2018

    @pepakriz
    ContributorAuthor

    Thanks for your answers. I like strict typing and I would like use it with this library. I want correct signatures in constructors - title?: string vs title: string. So this is reason for my proposal about skipping constructor call. My PR #1773 contains big hack in entity deserialization, but I don't have to write next hacks in entity constructors. Look at Doctrine ORM project. They do the same thing and they have lifecycle event postLoad (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-events)

    Edit: yeah, typeorm has similar event - http://typeorm.io/#/listeners-and-subscribers/afterload

  6. pleerock commented on Mar 29, 2018

    @pleerock
    Member

    Sorry, but I think avoiding a constructor and having users to use a listener instead is a bad idea. If you want to keep strictness you should initialize your properties, e.g. title: string = ""; - that's a proper resolution of the problem.

  7. pepakriz commented on Mar 29, 2018

    @pepakriz
    ContributorAuthor

    Why bad idea? In my opinion, deserialization is not the same as creating a new instance. I suggest skipping constructor only when an entity is deserialized from db, because the constructor is called without arguments and correct arguments cannot be estimated. The constructor should validate own consistency, so nobody can create an object in an invalid state. afterLoad event was the answer to the question: What if user wants to have something initialized after load?. But anyway, I've never used it.

  8. kbaryshnikov commented on Feb 10, 2019

    @kbaryshnikov

    In canonical DDD, you just cannot have an aggregate root entity constructor without a required argument (there's ID at least). Of course, there's an obvious workaround: using a named constructor (implemented with a static method) and declaring the constructor private kind of solves the issue. But a good ORM should not put such restrictions on model design.

    In Javascript, there is a proper way of creating a new instance without invoking constructor, no hacks required:

    Object.create(objectClass.prototype);
    
  9. pleerock commented on Feb 22, 2019

    @pleerock
    Member

    Reopening this issue and according PR.

  10. dgreene1 commented on Jul 24, 2019

    @dgreene1

    I have an example of you can continue to use strictPropertyInitialization but unfortunately it's sorta blocked by this other issue with migration:generate: #3835 (comment)

    I suppose that if you don't use migration:generate then you could still use this solution:

    import {
        Entity,
        PrimaryColumn
    } from "typeorm";
    
    @Entity()
    export class EntityThatCantBeGenerated  {
    
        @PrimaryColumn("varchar")
        public readonly id: string;
    
        constructor(input : { id : string }){
            this.id = input.id;
        }
    }

    As a temporary workaround (because I'm hoping this issue get's a PR that fixes the requirement of having a default constructor), you can make a private constructor and then create a static factory function instead. This allows you to have strict object initialization without the side-effect of breaking migrations (as described in #3835 (comment)). So here's the temporary workaround:

    import {
        Entity,
        PrimaryColumn
    } from "typeorm";
    
    interface IJustData {
        id: string;
    }
    
    @Entity()
    export class EntityThatCantBeGenerated implements IJustData   {
    
        @PrimaryColumn("varchar")
        public readonly id: string;
    
         /**
         * please use the static ".make" function instead. Read more here: https://github.com/typeorm/typeorm/issues/1772#issuecomment-514787854
         */
        private constructor(){} // <-- notice the private accessor
    
        public static make (input: IJustData){
             return Object.assign(new EntityThatCantBeGenerated(), input)
    }
    }

    The cool part is that TypeOrm is still capable of using the private constructor for things like migrations, but developers won't be able to use the unsafe default constructor. So essentially you get the advantages of strictPropertyInitialization.

  11. JulianKowalczuk commented on Aug 22, 2019

    @JulianKowalczuk

    @dgreene1 it's nice to test solution before post it 😄
    Your advice about using private constructor for is nice, but...
    this inside static method? I don't think so

    I would suggest:

    public static make (input: IJustData){
        return Object.assign(new EntityThatCantBeGenerated(), input)
    }
  12. dgreene1 commented on Aug 22, 2019

    @dgreene1

    Yes I found that after I posted it and forgot to update this example. I apologize but I was just trying to be helpful. And I do believe that the rough idea is still gets be going where the want to go.

    I’ve updated my example.

  13. 23 remaining items

  14. imnotjames commented on Jun 20, 2021

    @imnotjames
    Contributor

    I have a PR up which implements this.

    When deserializing from the database it will not call the constructor if you've set the connection option.

    In the future, perhaps we can make that the default. For now, to prevent some pretty severe breakage I think it's best to have it be opt-in.

  15. lucaswxp commented on Jun 28, 2021

    @lucaswxp

    @imnotjames That's nice, good work! I little confused as to "properties will not operate as expected" when using this, can you give one example?

  16. imnotjames commented on Jun 28, 2021

    @imnotjames
    Contributor

    @imnotjames That's nice, good work! I little confused as to "properties will not operate as expected" when using this, can you give one example?

    class Foo {
      bar = "baz"
    }
    

    Without the constructor, bar does not default to baz during testing.

  17. lucaswxp commented on Jun 28, 2021

    @lucaswxp

    @imnotjames I think that makes sense. What about private properties?

  18. imnotjames commented on Jun 28, 2021

    @imnotjames
    Contributor

    @imnotjames I think that makes sense. What about private properties?

    Yup.

    Also broken without the constructor.

    It's the same as you'll see anywhere else when this kind of thing happens.

  19. lucaswxp commented on Jun 28, 2021

    @lucaswxp

    @imnotjames I meant I don't understand what is broken in private properties? Should I make all my fields public or else they won't be de-serialized?

  20. imnotjames commented on Jun 28, 2021

    @imnotjames
    Contributor

    Only native private properties will have troubles.

    Hope this clarifies:

    class Example {
      // Public property with default
      foo = "bar";
    
      // Typescript Private property with default
      private bar = "baz";
    
      // Native Private Property with default
      #baz = "Hello World";
    
      notPrivate() {
        console.log(this.foo, this.bar);
      }
      
      all() {
        console.log(this.foo, this.bar, this.#baz);
      }
    }
    
    > const example1 = new Example();
    
    > example1.notPrivate(); // Note that this shows the two defaults
    bar baz
    
    > example1.boop() // Note that this shows all three
    bar baz Hello World
    
    > const example2 = Object.create(Example.prototype);
    
    > example2.notPrivate(); // Note that none of the default values get set
    undefined undefined
    
    > example2.boop(); // Note that this explodes :boom: 
    Uncaught:
    TypeError: Cannot read private member from an object whose class did not declare it
        at __classPrivateFieldGet ([eval].ts:3:94)
        at Example.boop ([eval].ts:1:10)
        at [eval].ts:1:10
        at Script.runInThisContext (node:vm:129:12)
        at exec (node_modules/ts-node/src/repl.ts:226:17)
        at node_modules/ts-node/src/repl.ts:216:27
        at Array.reduce (<anonymous>)
        at _eval (node_modules/ts-node/src/repl.ts:215:18)
        at evalCode (node_modules/ts-node/src/repl.ts:96:12)
        at REPLServer.nodeEval (node_modules/ts-node/src/repl.ts:115:16)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions