The process of accessing a method defined in one class from another class in TypeScript

I have a class with a handle() method that I have exported, and now I want to access this method in another class. Here is the code snippet:

customer.push.handler.ts

import { Inject } from "@nestjs/common";
import { EventsHandler, IEventHandler } from "@nestjs/cqrs";
import { CustomerPushEvent } from "../events/customer.push.events";
const admin = require('firebase-admin');

@EventsHandler(CustomerPushEvent)
export class CustomerPushEventHandler implements IEventHandler<CustomerPushEvent>{
  constructor(
     @Inject('Logger') private readonly log,
  ) {}

async handle(customerEvent:CustomerPushEvent){

    try{

        const message = {
            topic: String(customerEvent.customerId),
            notification: {
                title:'Dummy notification',
                body: 'New Shipment !!',
            },
            android: {
                collapse_key: 'messages',
                priority: 'HIGH',
            },
        };
      
        // Send a message to the device corresponding to the provided
        // registration token.
        admin
            .messaging()
            .send(message)
            .then(response => {
                console.log('Truck has been assigned:', message);
                console.log('Customer event',customerEvent);
            })
            .catch(error => {
                console.log('Error sending message:', error);
            });
    }
    catch(err){
        this.log.error(
            { error: err && err.message },
            'Error while communicating with FCM',
        );
    }
  }
}

another_class.ts

import { Inject } from "@nestjs/common";
import { ChatService } from "src/chats/chat.service";
import * as _ from 'lodash';
import { CustomerPushEventHandler } from "src/chats/event-handlers/customer.push.handler";

 export class CustomerNotificationEventhandler {
   constructor(@Inject('Logger') private readonly log,
    private readonly chatService: ChatService,
    @Inject('CustomerNotificationConsumer') private readonly customerNotifConsumer,
   ) {
       this.handle();
    }

   async handle() {
        
      //I need to find out how to access the handle() method defined in the CustomerPushEventHandler class 
   }
}     

Can someone help me with this?

Answer №1

For optimal functionality, ensure to include the CustomerPushEventHandler within the CustomerNotificationEventhandler constructor. Adjust the code accordingly:

import { Inject } from "@nestjs/common";
import { ChatService } from "src/chats/chat.service";
import * as _ from 'lodash';
import { CustomerPushEventHandler } from "src/chats/event-handlers/customer.push.handler";

export class CustomerNotificationEventhandler {
   constructor(@Inject('Logger') private readonly log,
    private readonly chatService: ChatService,
    @Inject('CustomerNotificationConsumer') private readonly customerNotifConsumer,
    private readonly customerPushEventHandler: CustomerPushEventHandler
   ) {
       this.handle();
    }

   async handle() {
        this.customerPushEventHandler.handle()
      //Accessing the handle() method declared in the CustomerPushEventHandler class 
   }
} 

Answer №2

To start, ensure that CustomerPushEventHandler is made injectable

@Injectable()
export class CustomerPushEventHandler implements IEventHandler<CustomerPushEvent>{
    // class properties & methods
}

Next, include CustomerPushEventHandler in the provider array within your module

@Module({
    providers: [
        CustomerPushEventHandler
    ],
})
export class AppModule {
}

Then proceed to inject it into the CustomerNotificationEventhandler

export class CustomerNotificationEventhandler {
    constructor( private readonly customerPushEventHandler: CustomerPushEventHandler
    ) {
    this.handle();
    }

    async handle() {
        // An instance of CustomerPushEvent is required at this point for further processing
        this.customerPushEventHandler.handle(customerEvent)
    }
}

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

Formatting Time in Angular 2 Using Typescript

Upon reviewing my date source, I found the following: TimeR ="2017-02-17 19:50:11 UTC"; Within the HTML file, I implemented this code snippet <span class="text-lg">{{TimeR | date: 'hh:mm'}}</span> The current output displays the t ...

Retrieving individual property from JSON with an array of values provided

Is there a way to extract names from the provided JSON, based on an array of IDs? [ { "id": 0, "name": "salesTransNo" }, { "id": 1, "name": "terminalNo" }, { "id": 2, "name": "salesTransDate" } ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

Why are my Typescript paths not resolving during the execution of Jest?

I am currently in the process of transitioning this project to jest by following these specific instructions. Everything seems to be working fine except for the files that make use of the paths configuration: "paths": { "@fs/*": ["./src/*"], ...

Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request. By enabling logging in TypeORM, I am able to observe the e ...

Find out if a dynamically imported component has finished loading in Nextjs

Here is a simplified version of my current situation import React, { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicImportedComponent = dynamic(() => import('Foo/baz'), { ssr: false, loading ...

Is TypeScript's nullish coalescing operator (??) supported by more browsers compared to JavaScript's equivalent?

When it comes to the nullish coalescing operator (??) in JavaScript, browser support is limited to newer browsers such as Chrome 80, Edge 80, and Firefox 72. Since TypeScript gets converted to JavaScript, do nullish coalescing operators also undergo some ...

Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file: subscribeUser() ...

Error: The function findUser is not declared on the Model data type in Typescript/Mongoose

I'm currently working on a project that involves implementing authentication using MongoDB, mongoose, and express with typescript. However, I've encountered an issue with typescript while trying to declare the type for findUser in my model.ts fil ...

Refining Typescript type with specific error for generics

Seeking assistance to comprehend the situation: TS playground The situation involves a store with an exec method, where narrowing down the type of exec param is crucial for a sub process. However, an error seems to arise due to the store type being generi ...

Typescript is failing to pick up process.env variables and is treating them as undefined, even though they are

I thought that by adding environment variables to environment.d.ts, they would have the correct types. I am using @types/node as a dev-dependency, and I have defined DATABASE_URL in my environment.d.ts like this: declare global { namespace NodeJS { ...

Is it necessary to use StyleProp<style> in React-Native, or can I simply write the styles without it?

My usual writing style is as follows: interface _props{ style?: TextStyle, } However, I'm considering adding StyleProp. What do you think? interface _props{ style?: StyleProp<TextStyle>, } If so, what are the reasons for doing so? ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

Developing a collection of components with customizable color variations using React

I am interested in creating a React component library where users can specify color variants. For instance, I want to use the following syntax: const customTheme = createCustomTheme({ button: { variants: { primary: 'primary ...

Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example. I'm uncertain about how to resolve it. Your assistance would be greatly appreciated. type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; typ ...

Error: Unable to iterate through posts due to a TypeError in next.js

Hi there, this is my first time asking for help here. I'm working on a simple app using Next.js and ran into an issue while following a tutorial: Unhandled Runtime Error TypeError: posts.map is not a function Source pages\posts\index.tsx (1 ...

Is it possible to associate a generic TypeScript type with another type by utilizing its generic parameters?

I am faced with a situation where I have a family of APIs consisting of various related generic types (along with associated constraints). To illustrate this, I have crafted an example using familiar types as placeholders for better understanding. As I wo ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Utilizing environment variables in the root files of your SvelteKit project: A guide

I have encountered an issue with my SvelteKit project which uses TypeScript and includes a .env file at the root. Additionally, I have added a drizzle.config.ts file at the root directory. The problem arises when I try to import DATABASE_HOST from $env/sta ...

Methods for excluding individual packages from bundling

I am looking to exclude specific packages from being bundled together in my application. The documentation provides guidance on how to do so: /** @type {import('next').NextConfig} */ const nextConfig = { serverExternalPackages: ['package- ...