Skip to content

Skip constructor when entity is loaded from database - #1773

Closed
pepakriz wants to merge 1 commit into
typeorm:masterfrom
pepakriz:free-constructor
Closed

pepakriz wants to merge 1 commit into
typeorm:masterfrom
pepakriz:free-constructor

Conversation

@pepakriz

@pepakriz pepakriz commented Mar 17, 2018 •

Copy link
Copy Markdown
Contributor

fixes #1772

@pepakriz pepakriz changed the title Skip constructor when entity is loaded from database Skip constructor when entity is loaded from database (closes #1772) Mar 17, 2018
@pepakriz pepakriz changed the title Skip constructor when entity is loaded from database (closes #1772) Skip constructor when entity is loaded from database (close #1772) Mar 17, 2018
@pepakriz pepakriz changed the title Skip constructor when entity is loaded from database (close #1772) Skip constructor when entity is loaded from database Mar 17, 2018
@pleerock

Copy link
Copy Markdown
Member

Looks like a big hack. What if user wants to have something initialized in the constructor?

@pleerock

Copy link
Copy Markdown
Member

Im going to close it, thanks for your efforts.

@pleerock pleerock closed this Mar 29, 2018
@pepakriz

pepakriz commented Mar 29, 2018 •

Copy link
Copy Markdown
Contributor Author

@pleerock I agree. It is big hack, but correct behavior in my opinion. I was inspired by Doctrine ORM. When entity is deserialized from db, constructor is omitted by reflection. So you have free constructor for initial checks and you don't need write special hack for undefined values.

To answer your question: If someone want to initialize something during deserialization from db, there is event (http://typeorm.io/#/listeners-and-subscribers/afterload)

@vimmerru

Copy link
Copy Markdown

@pleerock

I agree that calling constructor during deserialization is a wrong behavior and suggest to merge this.

  1. You noticed that constructor can have additional logic, but in the most cases this logic is invalid during deserialization process. Very simple example is assigning properties in constructor. As user doesn't expect undefined here it will cause crashing in runtime. Here are multiple bugs reported related to this.
  2. It is near impossible to use typeorm in 'strict' compiler mode. Especially, if you want to get some additional safety.
  3. Direct assignments of prototypes is more-less well known approach in js world.

@pleerock

Copy link
Copy Markdown
Member

Reopening this issue and according PR.

@pleerock pleerock reopened this Feb 22, 2019
@pleerock

Copy link
Copy Markdown
Member

I think I have change my mind since I see people have inconvenience with strict mode. @Kononnable @vlapo @havenchyk what you think about it?

@pepakriz

Copy link
Copy Markdown
Contributor Author

@pleerock Wow, glad to hear it! Tell me if you need some help

@Kononnable

Copy link
Copy Markdown
Contributor

There are reasons why some libraries requires such classes(e.g. entity classes) to have a constructor without parameters.

I'm good with both solutions:

  • not calling a constructor(since it's deserialization) as long as there is a way to easy propagate fields not saved in db(without a Column decorator)
  • use default values and constructor without parameters(current implementation)
    We can achieve same results with both of them so it's just a matter of preference.

// if target is set to a function (e.g. class) that can be created then create it
if (this.target instanceof Function)
return new (<any> this.target)();
return ObjectInstantiator.createInstanceWithoutConstructor(<any> this.target);

@XanderEmu XanderEmu Mar 13, 2019 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You know you could do something like:

const object = {};
Reflect.setPrototypeOf(object, this.target.prototype);
return object;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about Object.create(this.target.prototype); ? Looks more clear for me.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vlapo, yes Object.create will do the job, also Reflect.construct.
@XanderEmu not sure about Reflect.setPrototypeOf, see examples below

class Post {
    constructor(title) {
        console.log("Inside constructor for " + title);
        this._title = title;
    }
}

let post1 = new Post("post 1"); // > 'Inside constructor for post 1'
console.log(post1 instanceof Post); // > true (OK !)
console.log(post1._title); // > 'post 1'  (OK !)

let post2 = Reflect.construct(function() {}, [], Post);
console.log(post2 instanceof Post); // > true  (OK !)
console.log(post2._title); // > undefined  (OK !)

const object = {};
let post3 = Reflect.setPrototypeOf(object, Post.prototype);
console.log(post3 instanceof Post); // > false  (NOT OK !)

let post4 = Object.create(Post.prototype);
console.log(post4 instanceof Post); // > true  (OK !)
console.log(post4._title); // > undefined (OK !)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@XanderEmu Sorry, my bad, I messed it up, my example with Reflect.setPrototypeOf should have been coded properly:

const object = {};
Reflect.setPrototypeOf(object, Post.prototype);
post3 = object;
console.log(post3 instanceof Post); // > true

All good then !

@jtremback

jtremback commented Mar 13, 2019 •

Copy link
Copy Markdown

Will this PR make strict mode usable?

@XanderEmu

Copy link
Copy Markdown

Probably.

@pleerock

Copy link
Copy Markdown
Member

I can merge this branch if it fix all issues and will be created against next

@XanderEmu

XanderEmu commented Mar 16, 2019 •

Copy link
Copy Markdown

So I tried to do just that. I basically copied the code (submitted by @pepakriz into a new branch created against next, only I used JS Reflect instead of ObjectInstantiator).

https://github.com/XanderEmu/typeorm/tree/skip-constructor-when-entity-is-loaded-from-the-database

The tests are failing for entity-metadata-validator > initialized relations which should throw error if relation with initialized array was found on many-to-many relation.

I'm not sure how should I proceed. Basically, I don't understand why this is the case. Perhaps, with the change proposed by @pepakriz, it is not a problem anymore?

@pleerock

Copy link
Copy Markdown
Member

@XanderEmu I'll need to check tests on next, maybe they are failing not because of your changes. Just create a PR with all changes you propose, make sure your test is passing and I'll take of the rest once I get a chance to review and merge it.

@XanderEmu

Copy link
Copy Markdown

I'm afraid they weren't failing on next. I submitted a PR anyway:
#3845

@vlapo

vlapo commented Mar 19, 2019

Copy link
Copy Markdown
Contributor

I am good with both solution too. But I have to say that most of my entity classes have a lot of properties so mostly I use only one parameter with data to initialize and always optional.

Right now we have some issues and questions about parameters in constructor, after merge we will have question/issues about "non called constructors". So if this change will merged we have to update documentation and inform developers about deserialization process.

@jtremback

Copy link
Copy Markdown

@vlapo If you are using strict mode, Typescript complains if you have a non optional property on a class that is not explicitly instantiated in the constructor. This seems like a pretty integral part of type correctness to me.

If you are using an optional argument to instantiate your entities, are you doing a null check every time you access a property on an entity? If not, it seems like you are missing out on some of the correctness checking that Typescript could provide.

@nicomouss

nicomouss commented Mar 24, 2019 •

Copy link
Copy Markdown

@pepakriz nice work. I was about to submit a PR tackling the same issue, and I stumbled upon your work.

The example you have implemented in your test cases underline the right behavior the ORM should have in my opinion. With this solution, and with a Domain-Driven-Design standpoint: the business process of creating domain object and the technical process of re-creation/hydratation of these pre-existing domain objects are clearly separated.

NHibernate for example requires to have a default constructor on the domain classes (that you would usually hide by marking it as protected) to tackle the same design principle of separating an initial object creation (by the user) from its re-creation by the ORM later on.

Here the solution provided is even more elegant, as it does not require polluting domain classes with useless empty constructor (useless as they add no business meaning to your domain).

PS: just for information, I was using return Reflect.construct(function() {}, [], this.target); in my intended PR, end-result is same apparently I guess.

@nicomouss

nicomouss commented Mar 24, 2019 •

Copy link
Copy Markdown

Right now we have some issues and questions about parameters in constructor, after merge we will have question/issues about "non called constructors". So if this change will merged we have to update documentation and inform developers about deserialization process.

@vlapo Yes documentation should clearly state that TypeOrm will not call any constructor while re-constructing entities.

But again this design sounds more logical, so I am not sure it will raise more questions than before. In my case the question was more to understand "why is the ORM calling the constructor when re-constructing my entities". I add to put if/else within my constructors to avoid execution of some business code by the ORM, raising more questions from other members of the team asking why these if/else were here for ...

@pleerock

Copy link
Copy Markdown
Member

Closing in favor of #3845 . @pepakriz thanks for the contribution!

@pleerock pleerock closed this Mar 24, 2019
@pepakriz
pepakriz deleted the free-constructor branch March 24, 2019 18:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Skip constructor when entity is loaded from database

8 participants