Created
          August 19, 2025 12:04 
        
      - 
      
- 
        Save diogoko/4e53863c654607147bfef825621cf219 to your computer and use it in GitHub Desktop. 
    Nest.js pipe to call a service's method
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // Helper type to get all method names from a class | |
| type ExtractMethodNames<T> = { | |
| [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never; | |
| }[keyof T]; | |
| // Pipe to pass a value through a call to a method in an injectable service | |
| function ServicePipe<T extends new (...args: any[]) => any>( | |
| service: T, | |
| method: ExtractMethodNames<InstanceType<T>>, | |
| ): Type<PipeTransform> { | |
| class MixinServicePipe implements PipeTransform { | |
| constructor( | |
| @Inject(forwardRef(() => service)) | |
| private serviceInstance: InstanceType<T>, | |
| ) {} | |
| transform(value: unknown) { | |
| return this.serviceInstance[method](value); | |
| } | |
| } | |
| return mixin(MixinServicePipe); | |
| } | |
| // Utility type to extract the return type of an async method | |
| type ServicePipeResult<T, N extends ExtractMethodNames<T>> = T[N] extends ( | |
| ...args: any[] | |
| ) => any | |
| ? Awaited<ReturnType<T[N]>> | |
| : never; | |
| // Usage example | |
| @Controller('products') | |
| export class ProductController { | |
| @Get(':id') | |
| findOne( | |
| @Param('id', ServicePipe(ProductService, 'findOneById')) | |
| product: ServicePipeResult<ProductService, 'findOneById'>, | |
| ) { | |
| return product; | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment