Skip to content Skip to sidebar Skip to footer

Typeorm Aftersave() Triggers After Creation But When Queried, It Returns Null

I have an Entity called Trip. The structure is: What I want is whenever a new trip is created, the room column should be populated with ${tripId}_${someRandomStringHere}. So for e

Solution 1:

@AfterInsert method will just modify your JS object after inserting into DB is done. So thats reason why is your code not working. You have to use @BeforeInsert decorator. BeforeInsert will modify your JS entity/object before inserting/saving into DB.

Solution 2:

What it looks like is happening with your AfterInsert is that you are creating the random room string just fine, but you are not saving the value to the database, only using the return of the id so that you can create the string. What you could do in your AfterInsert is run the save() function from the EntityManager or RepositoryManger once more and commit the value to the database, similar to what you have happening in you Subscriber. I haven't dived too deep into the Subscriber/Listener vs Before-/AfterInsert decorators, so I can't give a deeper answer to your questions.

If you'd rather not make two commits to the database, you can always do a query for the most recent id and increment it by 1 (thus, matching what the new objects id should be) with something like

const maxId = awaitthis.tripRepository.findOne({select: ['id'], order: {id: "DESC"} });
const trip = awaitthis.tripRepository.create(data);
const randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
this.room =  `${maxId + 1}_${randomString}`
trip.driver = driver
awaitthis.tripRepository.save(trip)

It's a little clunky to look at, but it doesn't require two writes to the database (though you'll definitely need to ensure that after creation room and trip have the same id).

Your last option would be to create a Trigger in your database that does the same thing as your JavaScript code.

Solution 3:

You just use "this.save()" after all in createSocketRoom() function

https://i.stack.imgur.com/oUY8n.png my query after use that!!!

Post a Comment for "Typeorm Aftersave() Triggers After Creation But When Queried, It Returns Null"