从NestJS中微服务返回的Observable中提取值该怎么做?

huangapple go评论51阅读模式
英文:

How to Extract a Value from microservice returned Observable in NestJS?

问题

I am trying to implement NestJS Microservice to Validate my Bearer Token:

我正在尝试实现NestJS微服务以验证我的令牌:

Whenever I get TCP response from Microservice which decides whether token is valid or not, it return Observable object, I am unable to extract the response from that Observable, please help me. Not getting proper way to extract the value from Observable in Nestjs, already tried lastValueFrom from RXJS

每当我从决定令牌是否有效的微服务中获得TCP响应时,它返回一个Observable对象,我无法从该Observable中提取响应,请帮助我。我没有找到在Nestjs中从Observable中提取值的正确方法,已经尝试过RXJS中的lastValueFrom。

Here is the Controller to Make a call to Microservice(consumer/caller of microservice):

以下是用于调用微服务的控制器(微服务的消费者/调用者):

app.controller.ts
import { Body, Controller, Get, Post } from '@nestjs/common';
import { AppService } from './app.service';
import { PayloadDTO} from './payload.dto';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Post()
  createUserData(@Body() payload: PayloadDTO) {
    const token = header.authorization.replace('Bearer ', '');
    const isValidToken = this.appService.validateToken(token);

    if(isValidToken) {
      this.appService.createRecord(payload);
    } else {
      // Throw New UnauthorizedException
    }
  }
}
app.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { PayloadDTO } from './payload.dto';

@Injectable()
export class AppService {
  constructor(
    @Inject('COMMUNICATION') private readonly commClient: ClientProxy
  ) {}

  // service method to call and validate token
  validateToken(token: String) {
    // calling microservice by sending token
    const checkToken: Observable = this.commClient.send({cmd:'validate_token'}, token);
   
    // Unable to extract value from Observable here, it is returning observable object
    return extractedResponse; 
  } 

  // service method to create record   
  createRecord(payload: PayloadDTO) {
    // code related to creating a new Record
  }
}
app.controller.ts - Microservice Project
import { Controller, Get } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @MessagePattern({ cmd: 'validate_token' })
  validateToken() {
    return this.appService.checkToken();
  }
}

Please note that the code you provided has some issues, such as missing imports and undeclared variables. You may need to correct these issues to make the code functional.

英文:

I am trying to implement NestJS Microservice to Validate my Bearer Token:

Whenever I get TCP response from Microservice which decides whether token is valid or not, it return Observable object, I am unable to extract the response from that Observable, please help me. Not getting proper way to extract the value from Observable in Nestjs, already tried lastValueFrom from RXJS

Here is the Controller to Make a call to Microservice(consumer/caller of microservice):

app.controller.ts

    import { Body, Controller, Get, Post } from '@nestjs/common';
    import { AppService } from './app.service';
    import { PayloadDTO} from './payload.dto';
    
    @Controller()
    export class AppController {
      constructor(private readonly appService: AppService) {}
    
      @Get()
      getHello(): string {
        return this.appService.getHello();
      }
    
      @Post()
      createUserData(@Body() payload: PayloadDTO) {
        const token = header.authorization.replace('Bearer ', '')
        const isValidToken = this.appService.validateToken(token);
      }
       if(isValidToken) {
         this.appService.CreateRecord(Payload : PayloadDTO)
       } else {
          //Throw New UnathorizedException
       }
       
    }

app.service.ts

import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { PayloadDTO } from './payload.dto';

@Injectable()
export class AppService {

  constructor(
    @Inject('COMMUNICATION') private readonly commClient: ClientProxy
  ) {}

 // service method to call and validate token
  validateToken(token: String) {
    //calling microservice by sending token
    const checkToken: Observable = this.commClient.send({cmd:'validate_token'},token);
   
    //Unable to extract value from Observable here, it is returning observable object
    return extractedResponse; 
  } 

  // service method to create record   
  createRecord(payload: PayloadDTO) {
    //code related to creating new Record
  }
}

app.controller.ts - Microservice Project
    import { Controller, Get } from '@nestjs/common';
    import { MessagePattern } from '@nestjs/microservices';
    import { AppService } from './app.service';
    
    @Controller()
    export class AppController {
      constructor(private readonly appService: AppService) {}
    
      @MessagePattern({ cmd: 'validate_token' })
      validateToken() {
        return this.appService.checkToken();
      }
    }

答案1

得分: 1

以下是翻译好的部分:

在 Microservice Consumer/Caller app.controller.ts 中,我忘记在调用 this.appService.validateToken(token) 之前使用 await:

@Post()
async createUserData(@Body() payload: PayloadDTO) {
  const token = header.authorization.replace('Bearer ', '')
  const isValidToken = await this.appService.validateToken(token);
}

要从 Observable 转换/提取值:

在 app.service.ts 中(microservice 的使用者/调用者):

  1. 在 validateToken 前使用 async
  2. 使用 await lastValueFrom(checkToken)
  3. 返回 resp
// 调用和验证令牌的服务方法
async validateToken(token: String) {
  // 发送令牌调用微服务
  const checkToken = this.commClient.send({ cmd: 'validate_token' }, token);
  const resp = await lastValueFrom(checkToken);
  return resp;
}
英文:

Finally I got the answer on my own:

In Microservice Consumer/Caller app.controller.ts I forgot to use await before calling this.appService.validateToke(token)

      @Post()
      async createUserData(@Body() payload: PayloadDTO) {
        const token = header.authorization.replace('Bearer ', '')
        const isValidToken = await this.appService.validateToken(token);
      }

To convert/extract value from Observable:

In app.service.ts (consumer/caller of microservice) :

  1. use async before validateToken

  2. use await lastValueFrom(checkToken)

  3. return resp

    // service method to call and validate token
      async validateToken(token: String) {
        //calling microservice by sending token
        const checkToken = this.commClient.send({cmd:'validate_token'},token);
        const resp = await lastValueFrom(checkToken);
        reutn resp;
      } 
    

huangapple
  • 本文由 发表于 2023年2月9日 00:24:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定