我试图在不破坏 DI 层的情况下创建一个新实例,从而允许我的实例访问其构造函数中使用的所有可注入服务
我目前拥有的示例不允许我使用任何可注入服务:
const camera: Camera = new Camera(id, options);
Run Code Online (Sandbox Code Playgroud)
使用这种方法,相机类无法导入任何可注入的单例或类。
我在这里读到您可以使用它moduleRef来创建新实例,因此我尝试了以下操作:
const camera: Camera = await this.moduleRef.create(Camera);
Run Code Online (Sandbox Code Playgroud)
但现在的问题是,我无法传递ID和Options参数,唯一的解决方案是在初始化后立即使用设置器。
问题:
如何创建一个类的新实例(不是单例),由 Nest 的注入器创建并在最新版本的 NestJS 中创建时传递自定义参数?
我有一个应用程序,我根据 open-api 规范将 API 响应模式定义为纯 JavaScript 对象。目前我将其传递给ApiResponse@nestjs/swagger 中的装饰器,如下所示:
class CatsController {
@Get()
@ApiResponse({
status: 200,
schema: catSchema // plain js object imported from another file
})
getAll() {}
}
Run Code Online (Sandbox Code Playgroud)
这很好用。但是,输出 open-api 规范包含使用catSchema. 相反,我希望输出 swagger 文件在该部分下有 catSchema components,并$ref在 paths 部分中有一个对应的。
components:
schemas:
Cat:
properties:
name:
type: string
paths:
/cats/{id}:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Cat'
Run Code Online (Sandbox Code Playgroud)
到目前为止,唯一的方法似乎是将模式定义为 DTO 类并ApiProperty为每个类属性使用装饰器。就我而言,这意味着我必须将 open-api 规范中的所有普通对象模式重构为 DTO 类。
有没有办法将原始模式提供给库并获得预期的结果?
// instead of this:
class CatDto { …Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,它接收一个服务作为对控制器的依赖,到目前为止一切都很好,但我想找到一种方法,而不是声明该服务的具体实现,以便能够从控制器“询问”该服务实现的接口,用于解耦该服务的具体实现。在 Nest js 中这是如何完成的?
我正在开发基于 NestJS 的 api,并且正在使用 Swagger UI 文档。我想为我的所有控制器保留 @ApiBearerAuth() 的功能,但我希望将其作为全局功能。这样,每次我创建新的路线或端点时,它都会被覆盖。
来自https://docs.nestjs.com/openapi/security文档:
@ApiBearerAuth()
@Controller('cats')
export class CatsController {}
Run Code Online (Sandbox Code Playgroud)
这就是我现在正在关注的内容,但是有没有办法在全球范围内进行设置?
当发生未处理的错误时,前端会收到 500 错误,并且没有任何有关该错误的信息。它只是收到这个:
{
"statusCode": 500,
"message": "Internal server error"
}
Run Code Online (Sandbox Code Playgroud)
但是当我检查控制台时,我看到发生了什么以及错误消息是什么。在开发环境中还可以,但在生产环境中就很难搞清楚了。如何在生产中返回完整的错误消息,而不是像这样的简单消息"Internal server error"?
有谁知道我在哪里可以看到 AuthGuard('jwt') 中 canActivate 方法的完整代码?我意识到 canActivate 方法通过使用 console.log() 调用 JwtStrategy 验证方法,如下所示:
// jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly configService: ConfigService,
private readonly usersService: UsersService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: true,
secretOrKey: configService.get<string>('JWT_SECRET'),
});
}
async validate(payload: any) {
try {
const user = await this.usersService.getUserById(payload.id);
// console.log is here
console.log(user);
return user;
} catch (e) {
console.log(e);
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用原始的 canActivate 方法,则会调用 console.log 。我认为 JwtStrategy 是一个中间件,因此只要有请求就会调用 validate 方法。但是,当我尝试重写 canActivate 方法来添加授权时,不会调用 JwtStrategy …
嘿,我想创建一个具有唯一电子邮件的用户。我正在使用类验证器进行额外验证。我在这里找到了很多建议来实现这样的独特性:
@Schema()
export class User {
@Prop()
firstName!: string;
@Prop()
lastName!: string;
@Prop()
email!: {
type: String,
required: true,
index: true,
unique: true
};
@Prop({ nullable: true })
password?: string;
}
Run Code Online (Sandbox Code Playgroud)
但我抛出了一个错误:
Type 'UserDocument | null' is not assignable to type 'UserInput | null'.
Run Code Online (Sandbox Code Playgroud)
...我认为总的来说,这在 NestJS 中是不可能的。
我还通过添加唯一的道具找到了解决方案:
@Prop({
unique: true,
})
email!: string;
Run Code Online (Sandbox Code Playgroud)
...这有效,但随后我得到了完全不同的错误结构,并且我无法设置自定义错误。
我在 git 上看到的任何可行的解决方案都是测试服务中的唯一性并抛出错误。
为什么NestJS没有解决方案自动验证唯一性如预期?
NestJS 项目使用带有类验证器的 ValidationPipe来验证 POST 请求。在(react)前端使用相同的类验证器 DTO 会很好。
DTO 中的实体如何链接到反应元素?
这可能类似于如何同步前端和后端验证,但更侧重于特定工具。
jest
.spyOn(webService.prototype, 'isEnabled')
.mockImplementation(() => {
return Promise.resolve(true)
})
jest
.spyOn(webService.prototype, 'isEnabled')
.mockImplementation(() => {
return Promise.resolve(false)
})
Run Code Online (Sandbox Code Playgroud)
所以我想要的是如果参数中有“YES”字符串,则返回“true”。如果参数中有“NO”,则返回“false”。
函数的打字稿如下所示。
public isEnabled(featureId: string): Promise<boolean> {
return this.toggle.isEnabled(featureId)
}
Run Code Online (Sandbox Code Playgroud) 我有一个 Nestjs monorepo 应用程序,可以通过 Jest 进行工作测试。这与全局单元测试有关,该测试从 package.json 中的 Nestjs CLI 创建的配置中获取配置。
我的 storage.service.ts 使用jimp其方法之一来调整图像大小。
这具有@jimp/types依赖关系 取决于@jimp/gif取决于gifwrap。
对于在我的控制台中运行的每个测试,我都会看到以下错误:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at node_modules/.pnpm/gifwrap@0.9.2/node_modules/gifwrap/src/gifcodec.js:7:15
Run Code Online (Sandbox Code Playgroud)
我还使用 beforeAll() 和 afterAll() 钩子来关闭 Nestjs 模块。
笑话配置:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": ".",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "./coverage",
"testEnvironment": "node",
"roots": [
"<rootDir>/apps/",
"<rootDir>/libs/" …Run Code Online (Sandbox Code Playgroud) nestjs ×10
jestjs ×2
node.js ×2
typescript ×2
express ×1
mongodb ×1
mongoose ×1
nestjs-jwt ×1
passport-jwt ×1
passport.js ×1
reactjs ×1
swagger ×1
swagger-ui ×1
unique ×1