我阅读了以下文档描述的nest命令。
https://docs.nestjs.com/cli/scripts
根据该文件,必须添加以下内容package.json
"build": "nest build",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
Run Code Online (Sandbox Code Playgroud)
--watch和选项是什么--debug?
我已经使用 Spring Boot 开发微服务有一段时间了,使用 feign 客户端、REST 模板和 AMPQ 代理在每个微服务之间建立通信。
现在,我正在学习 NestJs 及其微服务方法。我注意到 Nestjs 使用 TCP 作为默认传输层,这与 Spring Boot 的方式不同。
为什么nestjs更喜欢那些传输层(TCP,AMPQ)而不是HTTP?HTTP 不是 REST 微服务的传输协议吗?
来自 NestJs 文档:
“微服务本质上是一个使用与 HTTP 不同的传输层的应用程序”
我\xe2\x80\x99m尽我所能地问这个问题\xe2\x80\x99t似乎得到了一个直接的答案。
\n因此,NestJS 有一种非常优雅的方法来使用装饰器来处理验证。也就是说,您可以使用所需的属性定义 DTO 类,并使用类验证器装饰器对它们进行注释。例如,假设我们有一条接受来自联系表单的输入的路线。
\nclass ContactInfoDTO {\n @IsString()\n @IsNotEmpty()\n name: string\n \n @IsEmail()\n email: string\n \n @IsString()\n @IsNotEmpty\n subject: string\n\n @IsString()\n @IsNotEmpty()\n body: string\n\n}\nRun Code Online (Sandbox Code Playgroud)\n这对于验证非常有用。如果我输入无效的电子邮件,它会按预期拒绝它。但是,这里\xe2\x80\x99是我的问题。输入清理怎么样?比如说,我在 body 参数中输入一些 JavaScript?比如说,我的身体看起来像这样:
\nbody: \xe2\x80\x9cHello <script>//some malicious code here</script>\xe2\x80\x9d\nRun Code Online (Sandbox Code Playgroud)\n现在,这个说法仍然被接受。尽管脚本标签没有转换为 HTML 实体,但这确实带来了一些安全风险。
\n所以,我的问题是 NestJS 是否有任何内置的清理机制?有这方面的适当文件吗?因为我不能\xe2\x80\x99t真正找到任何东西,尽管这种事情在网络开发的上下文中非常重要。
\n在 NestJS 中进行输入清理的最佳实践是什么\xe2\x80\x99?
\nIf I want to validate the role which user post to api to create if is unique of relation enterprise
@Injectable({ scope: Scope.REQUEST })
@ValidatorConstraint({ name: 'Ddd', async: true })
export class IsUnqiueForEnterpriseConstraint implements ValidatorConstraintInterface {
constructor(@Inject(REQUEST) private request: Request) {}
async validate(value: any, args: ValidationArguments) {
const { enterprise } = this.request.user as any
const { model } = args.constraints[0] as IParams;
if(!enterprise) return false;
if (!model) return false;
const repo = getManager().getRepository(model as ObjectType<any>);
const item = await …Run Code Online (Sandbox Code Playgroud) 我有一个关于设置环境变量的问题。
在官方文档中,它说在这种情况下使用ConfigModule,但我的情况是一个例外情况。
因为我想在构造函数的 super() 中使用它。
我的代码如下。
这种情况有什么解决办法吗?
如果您需要更多信息,请告诉我。
谢谢大家的支持!!
// jwt.strategy.ts
import { UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { UserRepository } from './user.repository';
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private configService: ConfigService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get('JWT_TOKEN'),
});
}
async validate(payload: JwtPayload) …Run Code Online (Sandbox Code Playgroud) 我有一个全局拦截器,需要初始化我自己的请求上下文 DTO,并且我希望可以在处理当前请求的控制器中访问此 DTO。
到目前为止我找到的解决方案是创建 Request 范围内的可注入 RequestContext 类:
import {
Injectable,
Scope
} from '@nestjs/common';
import { Request } from 'express';
import { IncomingHttpHeaders } from 'http';
@Injectable({ scope: Scope.REQUEST })
export class RequestContext {
public headers: IncomingHttpHeaders;
....
initialize(request: Request) {
this.headers = request.headers;
.....
}
}
Run Code Online (Sandbox Code Playgroud)
并将此类注入拦截器:
import {
NestInterceptor,
ExecutionContext,
CallHandler,
Injectable,
Inject
} from '@nestjs/common';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { RequestContext …Run Code Online (Sandbox Code Playgroud) 我想测试我的服务(位置服务)。在此位置服务中,我注入存储库和其他名为 GeoLocationService 的服务,但当我尝试模拟此 GeoLocationService 时陷入困境。
\n它给我一个错误
\nGeolocationService \xe2\x80\xba should be defined\n\n Nest can't resolve dependencies of the GeolocationService (?). Please make sure that the argument HttpService at index [0] is available in the RootTestModule context.\n\nRun Code Online (Sandbox Code Playgroud)\n这是提供商的代码
\n@Injectable()\nexport class LocationService {\n constructor(\n @Inject('LOCATION_REPOSITORY')\n private locationRepository: Repository<Location>,\n\n private geolocationService: GeolocationService, // this is actually what I ma trying to mock\n ) {}\n\n async getAllLocations(): Promise<Object> {\nreturn await this.locationRepository.find()\n }\n....\n}\n\nRun Code Online (Sandbox Code Playgroud)\n这是测试代码
\ndescribe('LocationService', () => {\n let service: …Run Code Online (Sandbox Code Playgroud) 我正在构建个人应用程序的后端,并且我有两个特定的模型/模式。一个用于产品,另一个用于订单。我想做以下事情:
订单需要具有以下结构的数组:
products: [
{
product: string;
quantity: number;
}
]
Run Code Online (Sandbox Code Playgroud)
产品应该是ObjectIdmongo,这需要“产品”模型的参考。
我怎样才能达到这个目标?我真的不知道如何用装饰器“输入”它@Prop()。
@Prop({
// HOW I DO THIS?
})
products: [{ quantity: number; product: mongoose.Types.ObjectId }];
Run Code Online (Sandbox Code Playgroud)
这是我的订单架构:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Document } from 'mongoose';
export type OrderDocument = Order & Document;
@Schema()
export class Order {
@Prop({ type: String, required: true })
name: string;
@Prop({ type: Number, min: 0, required: true }) …Run Code Online (Sandbox Code Playgroud) 我对 NodeJs 和 NestJs 有点陌生。我一直想知道在控制器内使用异步作为方法返回类型与在常规方法内执行异步操作有什么区别?如果此 API 上存在巨大流量(例如 40K 请求/分钟),NodeJs 如何处理这两种情况下的请求。在第二个示例中它是阻塞的,在第一个示例中是非阻塞的还是会以类似的方式工作?
例如:
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
async sample() {
return "1234";
}
}
Run Code Online (Sandbox Code Playgroud)
与
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
function sample() {
return await methodX();
}
async function methodX(){
return "1234"
}
Run Code Online (Sandbox Code Playgroud)
请忽略sample()和methodX()中的内容仅作为示例。
我正在使用 NestJS 7.6.11。我的控制器上有以下装饰器......
@Controller('private')
@ApiTags('MyObjects')
@ApiConsumes('application/json')
@ApiProduces('application/json')
@UseInterceptors(new JwtInterceptor())
export class MyController {
Run Code Online (Sandbox Code Playgroud)
是否有任何我可以添加的装饰器会导致生成 Swagger(OpenAPI 3)文档,以表明我的控制器中的所有方法都需要有一个“授权”标头?
编辑:作为回应,我添加了 @ApiHeader 所以我的控制器和方法看起来像
@
Controller('myendpoint')
@ApiTags('MyObject')
@ApiConsumes('application/json')
@ApiProduces('application/json')
@ApiHeader({
name: 'authorization',
description: 'Auth token',
})
@UseInterceptors(new JwtInterceptor())
export class MyObjectController {
...
@Get('/:id')
@ApiOkResponse({
description: 'OK',
type: Content,
})
@ApiBadRequestResponse()
@ApiInternalServerErrorResponse()
@ApiOperation({
summary: 'Get object by id',
description: 'Get object by id',
operationId: 'findObjectById',
})
findObjectById(@Req() req, @Param('id') id: string): Promise<MyObject> {
Run Code Online (Sandbox Code Playgroud)
但是当生成 swagger 文档时,尽管我可以输入“授权”标头值,
当我单击“执行”时,它不会包含在我的curl中,它生成为
curl -X GET "http://localhost:8060/myendpoint/abcdef" -H "accept: application/json"
Run Code Online (Sandbox Code Playgroud) nestjs ×10
node.js ×5
typescript ×5
javascript ×2
async-await ×1
http ×1
jestjs ×1
mongoose ×1
nestjs-jwt ×1
openapi ×1
swagger ×1