Combining 2 Observables in nestjs Interceptor: A Step-by-Step Guide

I am currently working on a NestJS interceptor to geolocate an address that is being sent through a REST API. Here is the code snippet:

export class PointsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    var myAddress = context.switchToHttp().getRequest().body;
    const geoCodingObservable = from(geocoder.geocode(myAddress));
    geoCodingObservable.subscribe(value => console.log(JSON.stringify(value)));

    return next.handle().pipe(map(value => console.log(value)))
  }

}

The output of this code includes:

  • a JSON object from the HTTP response:
{
  address: '123, Avenue des Champs Elysées, 75008 PARIS',
  _id: new ObjectId("64bd089088f925780705bbbd"),
  __v: 0
}
  • An object obtained from the geoCoder
[{"latitude":48.872438,"longitude":2.29811,"state":"75, Paris, Île-de-France","city":"Paris","zipcode":...}]

My goal is to combine all this information into a single JSON object that can be "pushed to the database". I have tried using merge and mergeWith, but without success.

Any assistance on this matter would be highly appreciated.

Thank you.

Answer №1

Have you ever considered using the tap method? Instead of subscribing, try utilizing from and then performing a tap on both operations. Please note that this approach has not been tested.

export class PointsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const monaddress = context.switchToHttp().getRequest().body;
    const geocodeResult = from(geocoder.geocode(monaddress));
    const geoCoder = await lastValueFrom(geocodeResult);

    return next.handle().pipe(
      tap(value => console.log(value)),
      map(value => {
        //1: Returning objects from both next.handle() and geoPremiseToObservable
        return {
          httpResponse: value,
          geoCoder: geoCoder
        };

       //2: Merging the geocoder response with the http response into a single object
        return {
          ...value,
          geoCoder: geoCoder
        };
      })
    );
  }
}

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

Encountering an endless loop within a data rest API in a React application

Currently, I am in the process of learning React and attempting to utilize the Poke API with my application. Unfortunately, I seem to have run into an infinite loop issue and I am feeling quite lost in terms of troubleshooting it. Below is a snippet of my ...

Encountering a Typescript error when trying to pass a function as a prop that returns SX style

Imagine a scenario where a parent component needs to pass down a function to modify the styles of a reusable child component: const getStyleProps: StyleProps<Theme> = (theme: Theme) => ({ mt: 1, '.Custom-CSS-to-update': { padding ...

Understanding the Use of Promises and Async/Await in Typescript

Struggling with asynchronous libraries in Typescript, I find myself looking for a way to wait for promises to be resolved without turning every method into an async function. Rather than transforming my entire object model into a chain of Promises and asyn ...

gulp-tsc cannot locate the src directory

I am currently working on developing a .NET Core application using Angular2, but I keep encountering the following error: /wwwroot/NodeLib/gulp-tsc/src/compiler.ts' not found. I'm having trouble pinpointing what I might be missing. tsconfig.js ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

By specifying the union type being used, the TypeScript compiler is informed

Imagine I have the following type: type TMyType = { a: string; b: number; c: number; d?: SpecialTypeA | SpecialTypeB | SpecialTypeC; } How can I specify in typescript that I am aware of the type of d in my (React) child components? I am hoping f ...

How can I only accept one of two specific function signatures in Typescript and reject any others?

Looking for an answer from the community on Typescript, require either of two function signatures In my code, I am handling a callback where I need to either pass an error or leave the first argument as undefined and pass data as the second argument. To ...

Encountered a TypeScript error in Vue 3 when attempting to access state within the setup method: "TS error -

Currently, I am working with Vue 3 and TypeScript. In the Setup function, I have defined some states like this: export default defineComponent({ setup() { const isLoadingSendData = ref(false) return { isLoadingSendData } }, methods: { ...

issue TS2322: The function returns a type of '() => string' which cannot be assigned to type 'string

I have recently started learning Angular 6. Below is the code I am currently working on: export class DateComponent implements OnInit { currentDate: string = new Date().toDateString; constructor() { } ngOnInit() { } } However, I am encounterin ...

Encountering a type error when attempting to filter TypeORM 0.3.5 by an enum column that is

I have the following configuration: export enum TestEnum { A = 'A', B = 'B' C = 'C' } @Entity() export class User { @PrimaryGeneratedColumn() id: number @Column({enum: TestEnum}) test: TestEnum } ...

The issue of TypeError arising while invoking a method within TypeScript Class Inheritance

Currently, I am developing a Node.js application with TypeScript. In this project, I have a base controller class named BaseController and a derived controller called SettingController. The intention is for the SettingController to utilize methods from the ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

What impact do passing children have on the occurrence of Typescript errors?

Recently, I came across a peculiar situation where the Typescript compiler appeared to be confused by passing the children prop to a component, leading to unsafe behavior. I am looking to create a component that can only accept the subtitle (text) and sub ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Angular Material Datepicker: Changing the input field format when the field value is updated

Currently, I am utilizing a mat-date-rang-input component from Angular Material. To customize the date format to dd/MM/yyyy, I made adjustments within Angular Material which is functioning correctly. <mat-form-field ngClass="filters_dateInterval&qu ...

Why is the table not sorting when I apply filters?

I am encountering an issue where the data filters and table sorting are not working together. When I apply filters, the sorting functionality stops working. The filters work fine independently, but once applied, they interfere with the sorting feature. Any ...