我是 Nestjs 的初学者,正在构建一个小型后端应用程序。我最初定义了一个用户类,这导致创建一个名为 user 的表。我随后删除了所有这些文件并创建了一个名为 people 的新类。现在,当我运行代码时,nestjs 创建了 2 个表 - 用户和人员。该代码工作正常,因为人员表已正确填充。如何让它停止创建另一个表?
我为 NestJs REST API 创建了一个自定义配置文件。这是应用程序正在侦听的端口的简单示例。
我有一个包含内容的 .env 文件
SERVER_PORT = 3000
Run Code Online (Sandbox Code Playgroud)
我的配置文件的示例
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as Joi from '@hapi/joi';
@Injectable()
export class ServerConfigService {
constructor(private readonly configService: ConfigService) {
const { error } = Joi.object({
port: Joi.number()
.port()
.required(),
}).validate({ port: this.port });
if (error) { // no error thrown
throw error;
}
console.log(typeof this.port); // type is string but should be number
}
public get port(): number { …Run Code Online (Sandbox Code Playgroud) 我正在测试我的控制器,但我在模拟该控制器的守卫时遇到问题。我的应用程序是使用 NestJs 版本 6.13.1 开发的
我可以覆盖一个守卫来嘲笑它,如下所示:
const fakeGuard: CanActivate = { canActivate: () => true };
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
CoreModule,
AuthModule,
PermissionsModule,
UsersModule
],
controllers: [UsersController],
})
.overrideGuard(AuthGuard('jwt')).useValue(fakeGuard) // When I have one guard in my controller it works right
.compile();
controller = module.get<UsersController>(UsersController);
app = module.createNestApplication();
app.init();
});
Run Code Online (Sandbox Code Playgroud)
但在我的场景中,我在控制器中定义了 2 个守卫
@UseGuards(AuthGuard('jwt'), PermissionGuard)
export class UsersController {
...
}
Run Code Online (Sandbox Code Playgroud)
我没有找到一种方法来嘲笑多个警卫。当我调用 overrideGuard 时,我尝试通过 2 个守卫,但是当我运行测试时,没有任何异常。但我知道,问题是因为我无法嘲笑那两个警卫。如果您遇到同样的问题,请与我分享您的解决方案,谢谢。
有人知道如何为 Nest 微服务编写 E2E 测试吗?给这个代码?
主要.ts
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP,
});
app.listen(() => console.log('Microservice is listening'));
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
应用程序控制器.ts
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
@Controller()
export class MathController {
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
return (data || []).reduce((a, b) => a + b);
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试按照Nest 文档中所述实现任务调度,但没有使用调度的服务的依赖注入示例。我想要的是在重复任务中使用注入的服务,但是当我执行以下操作时:
@Injectable()
export class MyWorkerService {
constructor(private readonly injectedService: MyInjectedService) {}
@Timeout(5000)
async doSomething(): {
console.log(this.injectedService); // undefined
this.injectedService.doStuff(); // TypeError: cannot read property 'doStuff' of undefined
}
}
Run Code Online (Sandbox Code Playgroud)
...依赖注入不起作用。两个服务都在同一模块中注册为提供者。
为什么会出现这种情况呢?我还能如何通过预定方法访问其他服务?
运行nestjs应用程序时遇到问题。
当前生态系统:
- Windows 10
-node版本:v12.10.0
-npm版本:6.10.3
-nestjs版本:6.14.2
重现步骤:
git clone https://github.com/gandra/nestjs-task-managament
cd nestjs-task-managament
npm i
npm run start
Run Code Online (Sandbox Code Playgroud)
收到以下错误:
CustomRepositoryCannotInheritRepositoryError: Custom entity repository TaskRepository cannot inherit Repository class without entity being set in the @EntityRepository decorator.
at new CustomRepositoryCannotInheritRepositoryError (C:\learn\node\nestjs-task-managament\node_modules\typeorm\error\CustomRepositoryCannotInheritRepositoryError.js:10:28)
at EntityManager.getCustomRepository (C:\learn\node\nestjs-task-managament\node_modules\typeorm\entity-manager\EntityManager.js:607:23)
at Connection.getCustomRepository (C:\learn\node\nestjs-task-managament\node_modules\typeorm\connection\Connection.js:365:29)
at getCustomRepository (C:\learn\node\nestjs-task-managament\node_modules\@nestjs\typeorm\dist\typeorm.providers.js:15:68)
at InstanceWrapper.useFactory [as metatype] (C:\learn\node\nestjs-task-managament\node_modules\@nestjs\typeorm\dist\typeorm.providers.js:20:24)
at Injector.instantiateClass (C:\learn\node\nestjs-task-managament\node_modules\@nestjs\core\injector\injector.js:291:55)
at callback (C:\learn\node\nestjs-task-managament\node_modules\@nestjs\core\injector\injector.js:75:41)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Injector.resolveConstructorParams (C:\learn\node\nestjs-task-managament\node_modules\@nestjs\core\injector\injector.js:116:24)
at …Run Code Online (Sandbox Code Playgroud) 我有一个BeforeInsertandAfterInsert钩子没有被调用。它所做的只是记录hook。我正在使用 Nestjs-graphql。
您可以运行此示例npm i,然后发送一个突变(playground 位于localhost:3000/graphql)body 处createUser(createInput:{password:"password" email:"test@test.com"})。它应该成功并记录hook。
钩子(没有记录任何内容):
@Entity('user')
export default class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
@IsEmail()
email: string;
@Column()
@Length(7, 42)
password: string;
@BeforeInsert()
@AfterInsert()
async validate() {
console.log("hook")
}
}
Run Code Online (Sandbox Code Playgroud)
它是从服务中调用的。插入不会引发错误,并here2会被记录:
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
) { }
async createNew(email: string, password: string): Promise<number> {
console.log("here2")
const hashedPassword = …Run Code Online (Sandbox Code Playgroud) 我需要对某些 API 调用进行事件跟踪(基于处理程序名称),它基本上是一个记录活动的函数。
目前我有一个拦截器可以执行此事件跟踪并且工作正常。
但问题是,每当出现错误时,我都会使用全局异常过滤器捕获它,并且这会立即返回响应,而无需输入拦截器和我的事件跟踪代码(我需要类名称、处理程序名称和返回的数据(如果可用))。
这是我的设置
应用程序模块.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
import { AuthModule } from './auth/auth.module';
import { MembersModule } from './members/members.module';
import { DatabaseConfigService } from './_database/database-config.service';
import { EventTrackerService } from './event-tracker/event-tracker.service';
import { LoggingInterceptor } from './_interceptors/logging.interceptor';
import { EventsTrackerInterceptor } from './_interceptors/events-tracker.interceptor';
import { AllExceptionsFilter } from './_filters/all-exception.filter';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 mongoose 并按照 Nestjs.com 中的相同内容动态配置连接,但在我的情况下,我需要注入工厂的服务将无法解析。这里是AppModule
@Injectable()
class Op implements MongooseOptionsFactory {
constructor(
@Inject(forwardRef(() => EndpointsService))
private endpointsService: EndpointsService) {
}
createMongooseOptions(): MongooseModuleOptions {
return {
uri: this.endpointsService.loginMongoDb
};
}
}
@Module({
imports: [
MongooseModule.forRootAsync({
useClass: Op,
inject: [EndpointsService] // having this doesn't help either
})
],
controllers: [AppController, UserController],
providers: [AppService,
EndpointsService, // is in the core module, but won't be seen
UserService]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)
非常简单(忽略操作名称,我稍后会将其移动到需要的地方)
这是EndpointsService
@Injectable()
export class EndpointsService {
private readonly …Run Code Online (Sandbox Code Playgroud) 我有一个 NestJS 控制器: search.controller.ts
import { Body, Controller, Post, Req, UseFilters } from '@nestjs/common';
import { HttpExceptionFilter } from '../exception/http-exception.filter';
import { SearchData } from './models/search-data.model';
import { SearchResults } from 'interfaces';
import { SearchService } from './search.service';
@Controller('')
@UseFilters(HttpExceptionFilter)
export class SearchController {
constructor(private searchService: SearchService) {}
@Post('api/search')
async searchDataById(
@Body() searchData: SearchData,
@Req() req
): Promise<SearchResults> {
return await this.searchService.getSearchResultsById(
searchData,
token
);
}
}
Run Code Online (Sandbox Code Playgroud)
此搜索控制器使用名为HttpExceptionFilter的过滤器。每当抛出HttpException时就会触发此过滤器。我创建了ServiceException,它扩展了HttpException。每当出现错误时,我都会抛出 new ServiceException() 。 …
nestjs ×10
typescript ×4
node.js ×2
typeorm ×2
e2e-testing ×1
graphql ×1
javascript ×1
joi ×1
mongoose ×1
sqlite ×1