Skip to content

Instantly share code, notes, and snippets.

@diogoko
Created August 19, 2025 12:04
Show Gist options
  • Save diogoko/4e53863c654607147bfef825621cf219 to your computer and use it in GitHub Desktop.
Save diogoko/4e53863c654607147bfef825621cf219 to your computer and use it in GitHub Desktop.
Nest.js pipe to call a service's method
// 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