import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Response as ExpressResponse } from 'express';
@Injectable()
export class ResponseAddContentRangeToHeaderInterceptor implements NestInterceptor {
intercept(context:ExecutionContext, next:CallHandler): Observable<any> {
const ResponseObj:ExpressResponse = context.switchToHttp().getResponse();
ResponseObj.setHeader('Access-Control-Expose-Headers', 'Content-Range' );
return next.handle();
}
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new ResponseAddContentRangeToHeaderInterceptor());
await app.listen(8080);
}
{
"message": ""// Ошибка валидации тут
}
{
"message": "",
"parent": {
"child": "" // Ошибка валидации тут
}
}
type IErrorMessage = Record<string, any>;
function formatErrorsHelper(errors: ValidationError[]): IErrorMessage[] {
return errors.map((item): IErrorMessage => {
const { property, constraints, children } = item;
const result: IErrorMessage = {};
if (constraints) {
result[property] = Object.values(constraints);
}
if (Array.isArray(children) && children.length > 0) {
result[property] = formatErrorsHelper(children);
}
return result;
});
}
{
"message": ["Сообщение об ошибке валидации"],
"parent": [
{
"child": ["Сообщение об ошибке валидации"]
}
]
}
// user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { JWTPayload } from '@/api/auth/auth.service';
export const User = createParamDecorator(
(userField: keyof JWTPayload, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user: JWTPayload | undefined = request.user;
return userField ? user?.[userField] : user;
},
);
export class AuthController {
constructor(private authService: AuthService) {}
@UseGuards(AuthGuard("jwt"))
@Get()
getPayload(@User() user: JWTPayload) {
// здесь мне нужно получить payload который был возвращен из jwt стратегии.
}
@UseGuards(AuthGuard("jwt"))
@Get(':id')
getUserId(@User('id') userId: string) {
// здесь мне нужно получить payload который был возвращен из jwt стратегии.
}
}
nestjs-i18n
.@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
private readonly jwtService: JwtService,
private readonly configService: ConfigService<EnvironmentVariables>,
private readonly userService: UserService,
private readonly i18n: I18nRequestScopeService, // Проблема тут
) {}
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
private readonly jwtService: JwtService,
private readonly configService: ConfigService<EnvironmentVariables>,
private readonly userService: UserService,
private readonly i18n: I18nService, // Меняем на I18nService и всё успешно работает ))
) {}