我正试图在nestjs中创建一个种子文件,问题是当我使用start:dev运行项目时,不知何故,nestjs也用main.ts文件启动了seed.ts文件。当我在prod/dev上运行项目时,如何使nestjs不启动种子文件,但只有在运行种子脚本时才能调用种子。
这是种子.ts代码
import { NestFactory } from '@nestjs/core'
import { Logger } from '@nestjs/common'
import { SeederModule } from './database/seeder.module'
import { Seeder } from './database/seeder'
async function bootstrap() {
NestFactory.createApplicationContext(SeederModule)
.then((appContext) => {
const logger = appContext.get(Logger)
const seeder = appContext.get(Seeder)
seeder
.seedRoles()
.then(() => {
logger.debug('Seeding Roles complete!')
})
.catch((error) => {
logger.error('Seeding Roles failed!')
throw error
})
seeder
.seedAdmin()
.then(() => {
logger.debug('Seeding Admin complete!')
})
.catch((error) => {
logger.error('Seeding Admin failed!')
throw error
})
.finally(() => appContext.close())
})
.catch((error) => {
throw error
})
}
bootstrap()
这是nestJS 的main.ts文件
import { Logger, ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { AppModule } from './modules/app/app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.enableCors()
const port = process.env.PORT || 3000
app.useGlobalPipes(new ValidationPipe())
await app
.listen(port)
.then(() => {
Logger.log(`App listening on port ${port}`)
})
.catch((err) => {
Logger.log(`Error while connecting to port ${port}`, err)
})
}
bootstrap()
这是package.json文件
{
"name": "jugg-website",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write "src/**/*.ts" "test/**/*.ts"",
"start": "nest start",
"start:dev": "link-module-alias && nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint "{src,apps,libs,test}/**/*.ts" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"seed": "ts-node -r tsconfig-paths/register src/seed.ts"
},
"dependencies": {
"@nestjs/common": "^7.6.13",
"@nestjs/core": "^7.6.13",
"@nestjs/jwt": "^7.2.0",
"@nestjs/passport": "^7.1.5",
"@nestjs/platform-express": "^7.6.13",
"@nestjs/typeorm": "^7.1.5",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"config": "^3.3.6",
"link-module-alias": "^1.2.0",
"passport": "^0.4.1",
"pg": "^8.5.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.6",
"typeorm": "^0.2.32"
},
"devDependencies": {
"@nestjs/cli": "^7.5.6",
"@nestjs/schematics": "^7.2.7",
"@nestjs/testing": "^7.6.13",
"@types/express": "^4.17.11",
"@types/jest": "^26.0.20",
"@types/node": "^14.14.31",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.15.2",
"@typescript-eslint/parser": "^4.15.2",
"eslint": "^7.20.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-jest": "^26.5.2",
"ts-loader": "^8.0.17",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\.spec\.ts$",
"transform": {
"^.+\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
您可以尝试在typeOrm中将KeepConnectionAlive选项设置为trueapp.module文件中的配置https://github.com/nestjs/typeorm/issues/61
我在运行e2e测试时遇到了这个错误。我发现默认的nestjs模板使用beforeEach
设置e2e测试,如下所示:
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
但由于我在规范文件中有不止一个测试(我是node.js开发的新手,所以不确定这样做是否正确,但不管怎样…(,发生的情况是app
在每个测试中初始化一次,这意味着它试图创建到数据库的多个连接。
解决方案非常简单。将beforeEach
更改为beforeAll
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
测试完成后不要忘记关闭应用程序
afterAll(async () => {
await app.close();
});
在我的案例中,问题出现在我的main.ts
文件中。我在没有注意到的情况下用TypeORM运行了两次模块,因为我试图访问我的ConfigService
,以便可以将环境变量用于除TypeORM数据库连接之外的其他服务。
导致错误的main.ts
:
...
async function bootstrap(): Promise<void> {
// the next line actually initiates a DB connection
const appContext = await NestFactory.createApplicationContext(MailModule);
const configService = appContext.get<ConfigService>(ConfigService);
// by now, we already established a DB connection, so trying to
// reinstantiate the connection will cause the error
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
MailModule,
{
transport: Transport.REDIS,
options: {
port: configService.get<number>('REDIS.PORT'),
host: configService.get<string>('REDIS.HOST'),
},
},
);
await app.listen();
}
bootstrap();
解决方案:
...
async function bootstrap(): Promise<void> {
const appContext = await NestFactory.createApplicationContext(MailModule);
// we close the redundant connection before we mount the app.
await getConnection('default').close();
const configService = appContext.get<ConfigService>(ConfigService);
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
MailModule,
{
transport: Transport.REDIS,
options: {
port: configService.get<number>('REDIS.PORT'),
host: configService.get<string>('REDIS.HOST'),
},
},
);
await app.listen();
}
bootstrap();