randombits
randombits

Reputation: 48460

Take JSON response and transform it to pass around application

In my NestJS app, I'm making a REST request to a remote API I do not have control over. The REST API has a response containing JSON, a large object, most of which I do not need. Let's assume hypothetically that we have a JSON object that looks like the following:

{
"foo": [
    1,
    2,
    3
],
"bar": {
    "nested": {
        "some_key": "some_val"
    }
}

}

What if in this case, after I make a request to this API, I want to pass around only a subset of the above. Something like a NestedDto that would look like the following:

import { IsNotEmpty, IsString } from 'class-validator'

export class NestedDto {
  @IsNotEmpty()
  @IsString()
  someKey: string
}

What is the best way for me to take the data that's being returned from the REST API and transform it into the above-using tools that NestJS offers? I want to be able to take responses from remote APIs and pass said data around inside of my NestJS app using my interface specifications.

Upvotes: 0

Views: 1448

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70211

All right, if you're just using Axios with no special configuration, you could do what you are already doping in Express by just mapping the response down to what you want. If you want to get a little fancy with it you could always implement some sort of class decorated with class-transformer decorators and use a plainToClass method mixed with the @Transform() decorator.

By the way, by default, NestJS provides an HttpModule that is a wrapper around Axios, but its responses are as RxJS Observables. If you decide to go with the observable route, you can use the observable operator map to do the mapping for you (you'll still have to provide mapping implementation though, like the plainToClass I mentioned above), but that is completely up to you.

Upvotes: 2

Related Questions