Home > Back-end >  Modify response with nestjs interceptor
Modify response with nestjs interceptor

Time:06-30

I have Interceptor for modify icon path like this:

@Injectable()
export class GetProgramIconInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
        return next.handle().pipe(
            map(data => {
                return {
                    ...data,
                    icon: generalFUnctions.getApplicationIcon(data.icon)
                };
            }),
        );
    }
}

and when I use this in my find method, it works correctly and modifies the icon path.

@UseInterceptors(GetProgramIconInterceptor)
async find(id: string): Promise<Application> {
    const application = await this.repository.findById(id);
     if (!application) throw new ApplicationNotFoundException();
     return application;
}

and when I use this Interceptor to the findAll method it doesn't work correctly and doesn't modify the path.

@UseInterceptors(GetProgramIconInterceptor)
async findAll(): Promise<Application[]> {
     return this.repository.find();
}

I know the result of the findAll method is an array and I can create another Interceptor for it. Is there any way to handle it with one Interceptor

CodePudding user response:

Since you are working with promises (And not already observable) results from the repository model functions (find and findById) when piping into the observable it means you are observing over repository or repository[]

Attaching a codesandbox of an example i have created mapping over resource that is possibly single object or array of objects.

The magic here is just making sure we have a conditional expression for when the resource is array or not

map((repositoryOrRespositories) => {
  if (Array.isArray(repositoryOrRespositories)) {
    return item.map((repository) => ({
      ...repository,
      icon: generalFUnctions.getApplicationIcon(repository.icon)
    }));
  } else {
    return { ...repositoryOrRespositories, icon: generalFUnctions.getApplicationIcon(repositoryOrRespositories.icon) };
  }
})

If the results from the repository model were observables you had to use iif expressions from rxjs.

  • Related