0%

nest.js - geting start

nest.js - geting start

Installation

1
npm i -g @nestjs/cli

Create a new project

1
nest new project-name

Create a new module

1
nest g module module-name

Create a new controller

1
nest g controller controller-name

Create a new service

1
nest g service service-name

Create a new pipe

1
nest g pipe pipe-name

Create a new resource

1
nest g resource resource-name

Database

Nest.js is database agnostic, you can use any database you want. For example, you can use TypeORM, Sequelize, Mongoose, etc.

Install TypeORM with mysql driver

1
npm install --save @nestjs/typeorm typeorm mysql2

Troubleshooting

Error: Nest can’t resolve dependencies of the SearchHistoryService (?). Please make sure that the argument “SearchHistoryRepository” at index [0] is available in the SearchHistoryModule context.

  1. 如果这个错误发生在一个module中(即不存在Module之间相互引用的情况),那么很可能是Module文件中缺少imports。加上下面这句:
1
2
3
4
5
6
7
8
9
10
11
12
import { Module } from '@nestjs/common';
import { SearchHistoryService } from './search_history.service';
import { SearchHistoryController } from './search_history.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { SearchHistory } from './entities/search_history.entity';

@Module({
imports: [TypeOrmModule.forFeature([SearchHistory])], // 这一句不能少!!!这个问题困扰了我一整天!
controllers: [SearchHistoryController],
providers: [SearchHistoryService],
})
export class SearchHistoryModule {}
  1. 如果这个错误发生在module交叉引用中,比如A module中的service引用了B module的service,那么需
    要:
  • 在B module中exports需要被引用的service
  • 在A module中imports B module
1
2
3
4
5
// A module
imports: [BModule],

// B module
exports: [BService],

Database data was deleted after start nest.js

将app.module.ts中的synchronize设置为false,这样每次启动都不会删除数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'xxx',
host: 'xxx',
port: 1234,
username: 'xxx',
password: 'xxx',
database: 'xxx',
entities: [xxx],
logging: true,
synchronize: false, // 这里设置为false!!!切记
}),
XXXModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}