import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import * as bcrypt from 'bcrypt'; export async function hashPassword(password: string) { const salt = await bcrypt.genSalt(); const passwordHash: string = await bcrypt.hash(password, salt); return passwordHash; } @Injectable() export class PasswordToHashInterceptor implements NestInterceptor { async hashPasswordInRequest(req) { const password = req.body.password; if (password) { const passwordHash = await hashPassword(password); req.body.passwordHash = passwordHash; } } filterPasswordHashFromResponse(data) { delete data.passwordHash; return data; } async intercept( context: ExecutionContext, next: CallHandler, ): Promise> { const req = context.switchToHttp().getRequest(); await this.hashPasswordInRequest(req); return next.handle().pipe(map(this.filterPasswordHashFromResponse)); } }