Created
April 13, 2023 08:58
-
-
Save ibayazit/dee57afc274297490e7265bcf4da63ab to your computer and use it in GitHub Desktop.
NestJS format outgoing response
This file contains 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
import { | |
UseInterceptors, | |
NestInterceptor, | |
ExecutionContext, | |
CallHandler | |
} from "@nestjs/common"; | |
import { Observable } from "rxjs"; | |
import { map } from "rxjs"; | |
import { plainToInstance } from "class-transformer"; | |
interface ClassConstructor { | |
new(...args: any[]): {} | |
} | |
export function Serialize(dto: ClassConstructor) { | |
return UseInterceptors(new SerializeInterceptor(dto)); | |
} | |
export class SerializeInterceptor implements NestInterceptor { | |
constructor(private dto: ClassConstructor) { } | |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> { | |
return next.handle().pipe( | |
map((data: ClassConstructor) => { | |
return { | |
data: plainToInstance(this.dto, data, { | |
excludeExtraneousValues: true | |
}) | |
}; | |
}) | |
); | |
} | |
} |
This file contains 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
import { Expose, Exclude } from "class-transformer"; | |
export class UserDto{ | |
@Expose() | |
id: number; | |
@Expose() | |
email: string; | |
@Exclude() | |
password: string; | |
} |
This file contains 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
... | |
import { Serialize } from '../interceptors/serialize.interceptor'; | |
import { UserDto } from './dtos/user.dto'; | |
@Serialize(UserDto) | |
@Controller('auth') | |
export class UsersController { | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment