You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Skip constructor when entity is loaded from database #1772
[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()exportclassPost{
@PrimaryGeneratedColumn()id: number;
@Column()privatetitle: string;constructor(title: string){if(title===undefined){thrownewError("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.
@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.
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.
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.
Reacted by Nathan Phillip Brink, Uladzimir Aleshka and Mihai Tomescu
Reacted by Vyacheslav Gudkov, Konstantin Baryshnikov, Sylvain Estevez, Christopher Chrapka, Gabriel Birke, Lucas Borges Fernandes, kwasimensah, Björn Fischer, Nishant Mahajan, Tobias Løfgren and 3 more
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.
Reacted by Vyacheslav Gudkov, Konstantin Baryshnikov, Björn Fischer, Nishant Mahajan, Tobias Løfgren and Will Dembinski
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);
Reacted by Mathias Iden, marrionluaka, Sylvain Estevez, Brian Bauer, Christopher Chrapka, soloraid, Ben Scholzen, Tim Lieberman, Zdeněk Trtil, Pieterjan and 12 more
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:
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";interfaceIJustData{id: string;}
@Entity()exportclassEntityThatCantBeGeneratedimplementsIJustData{
@PrimaryColumn("varchar")publicreadonlyid: string;/** * please use the static ".make" function instead. Read more here: https://github.com/typeorm/typeorm/issues/1772#issuecomment-514787854 */privateconstructor(){}// <-- notice the private accessorpublicstaticmake(input: IJustData){returnObject.assign(newEntityThatCantBeGenerated(),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.
@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
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.
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)
Activity
lodemo commentedon Mar 29, 2018
I think just checking the value instead of throwing an error would be a straightforward solution while maintaining the current functionality.
pepakriz commentedon Mar 29, 2018
@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.lodemo commentedon Mar 29, 2018
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.
pleerock commentedon Mar 29, 2018
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.
pepakriz commentedon Mar 29, 2018
Thanks for your answers. I like strict typing and I would like use it with this library. I want correct signatures in constructors -
title?: stringvstitle: 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 eventpostLoad(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
pleerock commentedon Mar 29, 2018
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.pepakriz commentedon Mar 29, 2018
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.
afterLoadevent was the answer to the question:What if user wants to have something initialized after load?. But anyway, I've never used it.kbaryshnikov commentedon Feb 10, 2019
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:
pleerock commentedon Feb 22, 2019
Reopening this issue and according PR.
dgreene1 commentedon Jul 24, 2019
I have an example of you can continue to use
strictPropertyInitializationbut unfortunately it's sorta blocked by this other issue withmigration:generate: #3835 (comment)I suppose that if you don't use
migration:generatethen you could still use this solution: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:
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.JulianKowalczuk commentedon Aug 22, 2019
@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:
dgreene1 commentedon Aug 22, 2019
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.
NoteEntity: Move constructor-code to create() method
23 remaining items
imnotjames commentedon Jun 20, 2021
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.
lucaswxp commentedon Jun 28, 2021
@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?
imnotjames commentedon Jun 28, 2021
Without the constructor,
bardoes not default tobazduring testing.lucaswxp commentedon Jun 28, 2021
@imnotjames I think that makes sense. What about private properties?
imnotjames commentedon Jun 28, 2021
Yup.
Also broken without the constructor.
It's the same as you'll see anywhere else when this kind of thing happens.
lucaswxp commentedon Jun 28, 2021
@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?
imnotjames commentedon Jun 28, 2021
Only native private properties will have troubles.
Hope this clarifies:
NoteEntity: Move constructor-code to create() method
NoteEntity: Move constructor-code to create() method
NoteEntity: Move constructor-code to create() method
NoteEntity: Move constructor-code to create() method
NoteEntity: Move constructor-code to create() method
NoteEntity: Move constructor-code to create() method