我正在尝试使用 DTO 为 Nest.js 中的控制器定义我的数据。
我正在学习教程
我已经在其中创建了我的 DTO src/controllers/cats/dto/create-cat.dto.js
export class CreateCatDto {
readonly name: string;
readonly age: number;
readonly breed: string;
}
Run Code Online (Sandbox Code Playgroud)
不过,我对如何将其导入应用程序感到困惑。文档实际上并没有说明它需要导入,所以我认为 nest 在幕后做了一些魔术?尽管我有一种感觉,但事实并非如此。
我想直接在我的控制器中导入它:
import { CreateCatDto } from './dto/create-cat.dto';
Run Code Online (Sandbox Code Playgroud)
但这会引发错误:
Unexpected token (2:11)
1 | export class CreateCatDto {
> 2 | readonly name: string;
| ^
3 | readonly age: number;
4 | readonly breed: string;
5 | }
Run Code Online (Sandbox Code Playgroud)
DTO 代码是直接从嵌套文档中删除的,因此代码不应该存在问题(尽管readonly name: string;看起来不像我以前遇到的 javascript)。
作为参考,这是我尝试使用 DTO 的猫控制器的其余部分
import { Controller, Bind, Get, …Run Code Online (Sandbox Code Playgroud) 我想在全局拦截器中使用服务。
我的代码如下所示:
import { VariablesService } from '../app/modules/variables/variables.service';
@Interceptor()
export class globalInterceptor implements NestInterceptor {
constructor(private service: VariablesService) {
console.log('contructor running', service); //getting null here
}
Run Code Online (Sandbox Code Playgroud)
在server.ts 上,我首先是这样初始化的:
app.useGlobalInterceptors(new globalInterceptor())
Run Code Online (Sandbox Code Playgroud)
但是在注入服务后我必须做一些修改,因为现在需要参数 globalInterceptor()
const variableService = await app.get<VariablesService>(VariablesService);
app.useGlobalInterceptors(new globalInterceptor(variableService));
Run Code Online (Sandbox Code Playgroud)
现在有什么问题是我得到service的null,我无法创建服务的对象。
这确实是一个意想不到的问题。
当我在终端输入“ npm run start”时,出现错误。
[Nest] 40671 - 2018-10-20 17:46:37 [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms
Error: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.
at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
at Function.Module.runMain (module.js:703:11)
at Object.<anonymous> (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at …Run Code Online (Sandbox Code Playgroud) 我有一个 REST API,我想通过 websocket 向客户端发送事件。如何在控制器或其他组件中注入 websocket 实例?
我正在使用 nest.js 并且我有一个 post 路由来向数据库添加新消息,所以我使用 postman 发送这样的对象数组:
[
{
"newsTitle" : "title1",
"newsDescription": "description1"
},
{
"newsTitle" : "title2",
"newsDescription": "description2"
}
]
Run Code Online (Sandbox Code Playgroud)
这是在我的控制器中发布的代码:
@Post()
async create(@Body() body: NewsDto[]) {
const len = body.length;
if (len == 1) {
}
else if (len > 1) {
}
return this.newsService.createNews(body);
}
Run Code Online (Sandbox Code Playgroud)
所以一切都在后期工作正常,并将数据保存在数据库中,但是当我使用 swagger 时,我得到了这个控制器的 dto 的模型,如下所示:
你可以看到这里没有显示 dto 的参数,我得到了“数组”标题,因为我使用@Body() body: NewsDto[]的是数组,如你所见
同样在帖子中我无法获取 JSON,因此我可以添加它或将其发布在另一个词中
那么如何处理这个问题,所以当数组的长度只有 1 个对象时,我返回 NewsDto 参数,如果数组的长度超过 1 个对象,那么也返回 NewsDto 参数而不是数组?
我试过使用
userRepository.find({
where: [
{
email: 'giberish@gmail.com',
},
{
username: 'thisismyusername',
},
]
});
Run Code Online (Sandbox Code Playgroud)
就像 typeorm 文档中解释的那样,但我收到此错误:
errmsg:
'Error getting filter : Error getting filter BSON field from doc = [{find user} {filter [[{email giberish@gmail.com}] [{username thisismyusername}]]} {returnKey false} {showRecordId false} {$clusterTime [{clusterTime 6660127540193001473} {signature [{hash [184 253 193 112 111 39 205 239 38 92 178 205 149 85 131 136 252 114 180 30]} {keyId 6637077103550398465}]}]}] : not bson []interface {} [[{email craftball@gmail.com}] [{username thisismyusername}]]\n\tat erh/mongonet/bsonutil.go:122\n\tat 10gen/atlasproxy/bson_util.go:32\n\tat 10gen/atlasproxy/commands_security.go:521\n\tat …Run Code Online (Sandbox Code Playgroud) 嗨,在一个测试套件上,我看来我有两个同一提供者的活动实例,一个实例用于实现,另一个实例用于实际实现。
我的结论基于这样一个事实:在测试中,我尝试用jest.fn调用替换方法,但仍然在我测试的服务上,该方法仍指向原始实现。
更奇怪的是,我能够模拟另一个执行完全相同的过程的服务,好像取决于这些服务的注入方式(它们来自容器图中的位置)是否起作用。
我将尝试分享一些片段,但是,当然,只有一个很小的回购实际上可以重现它,但是也许有人有一个见解:
beforeAll(async done => {
app = await Test.createTestingModule({
imports: [
SOME_MODULES,
],
providers: [
EssayApplicationService,
ReviewFacade,
ExamCacheResultService,
],
}).compile();
essayApplicationService = app.get<EssayApplicationService>(EssayApplicationService)
reviewFacade = app.get<ReviewFacade>(ReviewFacade)
examCacheResult = app.get<ExamCacheResultService>(ExamCacheResultService)
await app.init()
done()
})
Run Code Online (Sandbox Code Playgroud)
it('should invoke review only once', async done => {
reviewFacade.startReview = jest.fn() --> this works
examCacheResult.clearCachedResult = jest.fn() --> this fails
await essayApplicationService.finishApplication()
expect(reviewFacade.startReview).toHaveBeenCalledTimes(1)
expect(reviewFacade.startReview).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }))
expect(examCacheResult.clearCachedResult).toHaveBeenCalledTimes(1) ---> here this fails, although it's called!!
Run Code Online (Sandbox Code Playgroud)
因此,问题归结为以下事实:对于测试中的服务调用了这两种方法,我100%表示肯定,但是由于某种原因第二种方法并未被模拟代替
我正在尝试验证 get 请求的查询中出现的参数,但由于某种原因,验证管道无法识别查询的元素。
import {
Controller,
Post,
Query,
Body,
UseInterceptors,
Param,
Res,
Logger,
} from '@nestjs/common';
import { Crud, CrudController, Override } from '@nestjsx/crud';
import { OpenScheduleDto } from './open-schedule.dto';
@Crud(Schedule)
export class ScheduleController
implements CrudController<ScheduleService, Schedule> {
constructor(public service: ScheduleService) {}
get base(): CrudController<ScheduleService, Schedule> {
return this;
}
@Override()
async getMany(@Query() query: OpenScheduleDto) {
return query;
}
}
Run Code Online (Sandbox Code Playgroud)
OpenSchedule.dto
import { IsNumber, IsOptional, IsString } from 'class-validator';
export class OpenScheduleDto {
@IsNumber()
companyId: number;
@IsNumber()
@IsOptional()
professionalId: number; …Run Code Online (Sandbox Code Playgroud) 目前,我已经设法将 AuthGuard 与 JWT 身份验证结合使用,但我无法user在Roles.
我试图按照猫的例子,但我从来没有user定义过对象,你可以在第 14 行看到。
这是我的代码:
// auth.controller.ts
@Controller('auth')
@UseGuards(RolesGuard)
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('token')
async createToken(): Promise<any> {
return await this.authService.createToken();
}
@Post()
@UseGuards(AuthGuard())
@Roles('admin')
findAll() {
// this route is restricted by AuthGuard
// JWT strategy
return 'Super important info';
}
}
// auth.module.ts
@Module({
imports: [
SharedModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [SharedModule],
useFactory: async (configService: ConfigService) => ({
secretOrPrivateKey: …Run Code Online (Sandbox Code Playgroud) 有没有办法解决在类内部大量使用装饰器的问题?
这是我的NestJS应用程序中类的单个属性的示例,其中带有不完整的swagger文档装饰器:
@ApiModelProperty({
description: 'description',
})
@Expose()
@MaxLength(100, { message: 'message' })
@IsString({ message: 'message' })
@ValidateIf(address=> address.id !== null)
@NotEquals(undefined, { message: 'message' })
address: string;
Run Code Online (Sandbox Code Playgroud)
这很快就变得庞大而丑陋。有什么方法可以使代码看起来更简洁,在另一个文件中定义装饰器?
nestjs ×10
javascript ×8
node.js ×8
typescript ×8
typeorm ×2
decorator ×1
interceptor ×1
jestjs ×1
mongodb ×1
socket.io ×1
swagger ×1