Event typeORM on afterUpdate in NestJS

After every update of my data in the log table, I want to insert an entry into another table. To achieve this, I have created an EntitySubscriberInterface. The event is triggering correctly, but the entity array does not include the updated id.

 async afterUpdate(event: UpdateEvent<any>) {
    console.log(event.entity);
    const book = event.entity;
    const authorId = book.authorId;
    console.log(newAuthorId);       
// this.myService.insertHistory(authorId , event.entity);

}

If anyone has any ideas or suggestions, they would be greatly appreciated. Thanks.

Answer №1

To retrieve data from a database, you have two options: either execute a findOne query as suggested by @Bramovic44, or implement an afterLoad method that is triggered after an entity has been loaded.

Below is a simple example to demonstrate this concept:

export class EntitySubscriber implements EntitySubscriberInterface<SomeEntity> {
  someEntity: SomeEntity;

  listenTo() {
    return SomeEntity;
  }

  afterLoad(someEntity: SomeEntity) {
    this.someEntity = someEntity;
  }

  async afterUpdate(event: UpdateEvent<SomeEntity>): Promise<any> {
    event.entity; // returns updated properties in entity
    this.someEntity; // returns entity prior to update with all properties
  }

Answer №2

The afterInsert method provides access to information, while with the afterUpdate method, you need to query the database for the entity.

const item = await connection
      .getRepository(item)
      .findOne(event.entity.id);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining enum values to create a new data type

Exploring the implementation of type safety in a particular situation. Let’s consider the following: const enum Color { red = 'red', blue = 'blue', } const enum Shape { rectangle = 'rectangle', square = 'square ...

Tips for creating an Angular component that can receive a single value from a choice of two different lists

My angular component requires a value that belongs to one of two lists. For example: @Input() public type!: enumA | enumB; However, this setup becomes problematic when the enums share values or are linked together in a way I find undesirable. I would pre ...

Is there a way to import TypeScript modules from node_modules using browserify?

After successfully running tsc, I am facing difficulty understanding how to import TypeScript modules from node modules. The crucial section of my gulp file is as follows: gulp.task('compile-ts', ['clean'], function(){ var sourceTsF ...

Is it possible to execute TypeScript class methods in asynchronous mode without causing the main thread to be blocked?

Creating an app that retrieves attachments from specific messages in my Outlook mail and stores the data in MongoDB. The challenge lies in the time-consuming process of receiving these attachments. To address this, I aim to execute the task in a separate t ...

Unable to simulate a returned value from an import in Jest

Within my module, I have a function called shuffle<T>(a: T[]): T[] that is exported by the random module. While testing two methods in another class that rely on this function, I need to mock it. Here's how I attempted to do so: jest.mock(' ...

The function waitForAngularEnabled does not exist

Currently, I am conducting end-to-end tests for an Angular application. For the login process, it needs to exit the app, so here is what I am doing: browser.waitForAngularEnabled(false); //login browser.waitForAngularEnabled(true); While this approac ...

NodeJS function does not pause for the PostgreSQL database call despite using await keyword

I am attempting to recursively insert entries into the database where each entry depends on the previous one (the ID of the previous entry will be the child_id of the next entry). However, I am facing difficulties in getting async/await to work correctly. ...

Challenges with Initializing Angular 2 Router

I'm encountering a problem with the Angular 2 Router. My goal is to navigate through my application using a function that utilizes the navigate function from the Router, similar to how it's done in the official example. Here's what I curren ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a variab ...

Experiencing complications with an Angular 2 router

When a user logs into the system, they are greeted with a navigation bar featuring options like Dashboard, Customers, and Product. Below is an excerpt from my routes file: app.routing.ts export const router: Routes = [ { path: '', redir ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Accessing a JSON value in SCSS for localization

I have a JSON file containing all the values that I want to use for internalization in my app. On the HTML side, I am able to retrieve the values, but on the CSS side, I am using a "before" pseudo-element. In my HTML, I am using the class "menu-input" li ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Updating JWT token with Angular 5 Http Interceptor

I have successfully implemented token saving, retrieving logic and a refreshing call. However, I am facing an issue where when I intercept a 403 error in my HttpInterceptor, other simultaneous calls also trigger a token refresh. I would like to find a wa ...

When the client's URL is http://localhost:4200, the server is failing to respond to the post request

I have encountered a strange issue while working on an Angular app that communicates with an Express server. This problem has been perplexing me for the past few days and goes as follows: Upon loading the web page, I initiate a post request to the server. ...

Protected HTTP Live Streaming 128-bit AES encryption key location

After encrypting a video using HLS AES-128 with the apple tool, I have generated an m3u8 file that looks like this: #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:0 #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-KEY:METHOD=AES-128,URI="https://xxxxx.com/api/ ...

Facing an issue with ngx quill editor malfunctioning when utilizing the cdkDrag directive from Angular Material

Having trouble with the focus on the Quill editor or typing content while using the cdkDrag directive from Angular Material. Check out my code on StackBlitz: https://stackblitz.com/edit/angular-ivy-xalouc Issue Summary: The editor is only editable when ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

Is there a specific type in typescript that represents every iterable object?

We have a unique function shown below: export const transformUndefinedToNull = (obj) => { const convert = (o) => { Object.keys(o).forEach((key) => { const value = o[key]; if (value === undefined) { o[key] = null; } ...

Tips for automatically adjusting the row height in a table with a static header

On my page, I have a header, footer, and a single table with a fixed header. You can check out the code in the sandbox (make sure to open the results view in a new window). Click here for the code sandbox I am looking to extend the rows section so that i ...