Documention Update: Pipes with config AND dependency
See original GitHub issueBug Report
Current behavior
Your docs give great examples of how to configure a Pipe for DI or an options object but not both. The use case below would allow me to create one pipe that I could configure for any request object by supplying the property name containing the file path value. As it stands, I would basically need to create the same pipe over and over again for requests with different request signatures. This example is contrived but hopefully you could see how it could be beneficial.
Input Code
pipe.ts
@Injectable()
export class FileExistsPipe implements PipeTransform {
constructor(private filePath: string, db: DatabaseService) { }
async transform(value: any, metadata: ArgumentMetadata) {
const path = value[this.filePath];
const doesExist = await this.db.file(path).exists()
if(!doesExist) throw new BadRequestException();
return value;
}
}
controller.ts
interface JobRequest {
input: 'path/to/file/on/server'
}
@Controller('transcode')
export class TranscodeController {
@Post()
async transcode (
@Body( new FileExistsPipe('input')) transcodeRequest: JobRequest) {
return await this.videoProducer.addJob(transcodeRequest);
}
Expected behavior
The above solution doesn’t work because the call to new FileExistsPipe('input')
needs two arguments, the second being the DatabaseService dependency. The other option would be to do @Body(FileExistsPipe)
but then I wouldn’t be able to pass my property name to my pipe to look up in the request object.
Possible Solution
I have posted this question on stackoverflow, here, in case you would prefer to leave the documentation as is.
Issue Analytics
- State:
- Created 3 years ago
- Comments:14 (6 by maintainers)
@tommyc38 I just checked your repo (sorry for missing it before). Your
DatabaseService
isundefined
in theFIleExistPipe
because you use the pipe inAppController
.AppController
will be resolved before theDatabaseModule
gets resolved. You can useforwardRef()
to inject theDatabaseService
in your pipe if you are going to use the pipe inAppController
. The good practice here is to have feature controllers provided in feature modules.this is the fix btw
https://github.com/tommyc38/nest-pipe-repro
@nartc , I included instructions in the README. Should be pretty straightforward. Note, I am also creating another Nest repro and am using this for that as well.