NestJS - 将服务注入管道以从数据库中获取

NestJS - Inject service into Pipe to fetch from DB

我正在尝试将服务注入 PipeTransform class 以从数据库中获取条目。

我已经尝试了这个答案中的解决方案,但是我得到了一个不同的错误 Inject service into pipe in NestJs

sample.pipe.ts

@Injectable()
export class SamplePipe implements PipeTransform<any> {
  constructor(private readonly sampleService: SampleService) {}

  async transform(value: any, metadata: ArgumentMetadata) {
    const id = parseInt(value, 10);
    let sample: SampleEntiy = await this.sampleService.findOne(id);
    if (!sample) throw new NotFoundException('Sample Not Found');
    return sample;
  }
}

sample.controller.ts

@Controller('sample')
export class SampleController {
  constructor(private readonly sampleService: SampleService) {}

  @Get(':id')
  async findOne(@Param('id', SamplePipe) id: SampleEntiy): Promise<SampleEntiy> {
    return sample;
  }

}

我在控制器 return sample 收到以下错误

Type '<T>(notifier: Observable<any>) => MonoTypeOperatorFunction<T>' is missing the following properties from type 'SampleEntiy': id, value, isActivets(2739)

在使用 any 强制它 return 时,我在浏览器中收到以下响应

function sample(notifier) {
return lift_1.operate(function (source, subscriber) {
var hasValue = false;
var lastValue = null;
source.subscribe(new OperatorSubscriber_1.OperatorSubscriber(subscriber, function (value) {
hasValue = true;
lastValue = value;
}));
var emit = function () {
if (hasValue) {
hasValue = false;
var value = lastValue;
lastValue = null;
subscriber.next(value);
}
};
notifier.subscribe(new OperatorSubscriber_1.OperatorSubscriber(subscriber, emit, noop_1.noop));
});
}

我知道这是与异步有关的。 docs 表示支持异步

First, note that the transform() method is marked as async. This is possible because Nest supports both synchronous and asynchronous pipes. We make this method async because some of the class-validator validations can be async (utilize Promises).

我正在尝试 docs 中提到的内容:

Another useful transformation case would be to select an existing user entity from the database using an id supplied in the request:

@Get(':id') 
findOne(@Param('id', UserByIdPipe) userEntity:UserEntity) {
  return userEntity; 
} 

您正在 return 使用 rxjs 包中的 sample 函数(原文如此!):

@Get(':id')
async findOne(@Param('id', SamplePipe) id: SampleEntiy): Promise<SampleEntiy> {
  return sample;
}

该参数称为 id,您可能打算将其 return 改名,或者更好的是,将其重命名为 sample:

@Get(':id')
async findOne(@Param('id', SamplePipe) sample: SampleEntiy): Promise<SampleEntiy> {
  return sample;
}