Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
wetland update after persist

Code

let wetland : Wetland.Wetland = RFY.wetland;
let manager : Wetland.Scope = wetland.getManager();

//Instantiate entity, persist
let author = new entities.Author();
manager.persist(author);

//Set initial value
author.name = "This is the initial name";

//Flush
await manager.flush().catch((err: Error) =>
{
    console.log("Problem flushing author: " + err);
});

//Make additional changes
author.name = "This is the changed name";

//Flush again
await manager.flush().catch((err: Error) =>
{
    console.log("Problem flushing author: " + err);
});

//Grab from db and check actual persisted value
author = await manager.getRepository(entities.Author).findOne({ id:author.id });

console.log("Persisted name: ",author.name);

Output

Persisted name:  This is the initial name

Expected the second flushed value, "This is the changed name"

@RWOverdijk

This comment has been minimized.

Copy link

RWOverdijk commented Feb 24, 2018

Interesting question. This shouldn't work. I understand why you'd think so, because this is a case that doesn't happen often, and so hasn't been asked about a lot. Also because I didn't document it properly, for which I'm sorry.

The solution

Newly created classes aren't tracked for changes. This is a performance consideration. 99% of the time, new entities are created, persisted, and forgotten about. Then the Scope instance gets destroyed. On the next request, a new scope gets created.
In your case, you want to tell wetland to track your new entity, because you'll be persisting it and then make changes to it. The only change you need to make is in your let author = line:

const author = manager.attach(new entities.Author(), true);

You can see this working by logging the the dirty entities after flushing and changing it again:

console.log(manager.getUnitOfWork().getDirtyObjects());

Now, wetland will track your entity.

Why this works

Wetland uses Proxy to bring epic performance and convenience. It only tracks entities that have been attached to the unit of work. Which is what attach does. The second argument, set to true, enables proxying on your entity. The longer way of activating proxying would be by using the proxy method "activateProxying" on your entity, which would look like this:

const author = manager.attach(new entities.Author());

author.activateProxying();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.