gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:45:20 42 4
gpt4 key购买 nike

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

我已经尝试了这个答案中的解决方案,但是我得到了一个不同的错误 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;
}

}

我在 Controller 的 return sample 处得到以下错误

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

使用 any 强制它返回时,我在浏览器中得到以下响应

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;
}

最佳答案

您要从此处的 rxjs 包返回 sample 函数(原文如此!):

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

参数名为 id,您可能打算返回它,或者更好的是,将其重命名为 sample:

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

关于NestJS - 将服务注入(inject)管道以从数据库中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69177760/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com