我遵循了文档,并且能够为响应映射添加一个拦截器。
我想要一个一致的 json 格式输出用于响应。
我如何使用拦截器或其他比这种方法更好的方法来实现这一点。
{
"statusCode": 201,
"message": "Custom Dynamic Message"
"data": {
// properties
meta: {}
}
}
Run Code Online (Sandbox Code Playgroud)
transform.interceptor.ts
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Response<T> {
statusCode: number;
data: T;
}
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, Response<T>> {
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<Response<T>> {
return next
.handle()
.pipe(
map((data) => ({
statusCode: context.switchToHttp().getResponse().statusCode,
data,
})),
);
} …Run Code Online (Sandbox Code Playgroud) 我尝试在AppController 中创建一个新方法,但它没有反映更改。我什至尝试更改默认的getHello()方法,但它输出“Hello World!” . 这怎么可能?
失眠
应用控制器
应用服务
ConfigService我正在尝试在我的中使用,users.module.ts但我得到了
错误:Nest 无法解析 UsersService(UserRepository、HttpService、?)的依赖项。请确保索引 [2] 处的参数 ConfigService 在 UsersModule 上下文中可用。
潜在的解决方案:
我已将 ConfigModule 导入到我的 UsersModule 中,但仍然无法正常工作:(
应用程序模块.ts
@Module({
imports: [
ConfigModule.forRoot({
expandVariables: true,
}),
TypeOrmModule.forRoot(),
UsersModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
用户.module.ts
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule, HttpModule, TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
Run Code Online (Sandbox Code Playgroud)
用户.service.ts
export class UsersService { …Run Code Online (Sandbox Code Playgroud) 我试图在我的 swagger 文档路径中添加摘要,但我无法找到合适的装饰器来定义摘要。
有一些路线我没有指定任何 DTO。因此,我想手动添加该端点的请求正文。
用户控制器.ts
@Controller('users')
@ApiTags('User')
@ApiBearerAuth()
export class UsersController {
constructor(private readonly service: UsersService) {}
@Get()
async findAll() {
const data = await this.service.findAll();
return {
statusCode: 200,
message: 'Users retrieved successfully',
data,
};
}
}
Run Code Online (Sandbox Code Playgroud)
auth.controller.ts
@UseGuards(AuthGuard('local'))
@Post('login')
@ApiParam({
name: 'email',
type: 'string'
})
@ApiParam({
name: 'password',
type: 'string'
})
async login(@Request() req) {
return this.authService.login(req.user);
}
Run Code Online (Sandbox Code Playgroud)