nestjs monorepo模式

1711293058發表於2020-08-15

專案環境

  1. mac系統
  2. node v12.18.0
  3. mysql 假設已經建立了test資料庫

初始化專案

nest new test

建立admin子應用

#子應用
nest g mo admin #自動生成apps/admin目錄
#建立使用者模組
nest g mo user #user.model
nest g s user #user.service
nest g co user #user.controller
#公用庫
nest g lib db #自動生成libs目錄

在libs/db目錄下面建立實體目錄,新建user.entitiy.ts

import { Column, Entity,PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'user' })
export class UserEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column({ length: 20 ,comment:"使用者名稱"})
    username: string;

    @Column({length:60, comment:"密碼"})
    password: string;
}

最終目錄結構如下

test
  | --- apps
     | --- admin //admin應用
        | --- src
           | --- main.ts
           | --- app.module.ts
           | --- user //使用者模組
              | --- user.module.ts
              | --- user.service.ts
              | --- user.controller.ts
   | --- libs
      | --- db
         | --- src
           | --- db.module.ts //公用db模組
           | --- db.service.ts
           | --- entities //公用實體目錄
              | --- user.entity.ts //使用者實體

下載包

yarn add mysql @nestjs/typeorm typeorm

資料庫配置

db.module.ts

@Module({
    imports: [
        TypeOrmModule.forRoot({
            type: 'mysql',
            host: '127.0.0.1',
            port: 3306,
            username: 'username',
            password: 'password',
            database: 'test',
            entities: [
              __dirname +  "/entities/*.ts" //這裡有問題是 
            ],
            synchronize: true,
        })
    ],
    providers: [DbService ],
    exports: [DbService],
})
export class DbModule {
}

組合模組

app.module.ts

@Module({
    imports: [
        DbModule, //引入db公用模組,別忘記了!
        UserModule
    ],
    controllers: [AppController],
    providers: [AppService],
})

export class AppModule { }

業務程式碼

user.controller.ts

import { Controller, Post,Body, Param } from '@nestjs/common';
import { UserService } from './user.service';


@Controller('user')
export class UserController {

    constructor(private readonly usersService: UserService) {
    }

    @Post()
    create(@Body() data) {
        return this.usersService.create(data)
    }

}

user.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getRepository } from 'typeorm';
import {UserEntity} from "@libs/db/entities/user.entity";


@Injectable()
export class UserService {

    constructor(
        @InjectRepository(UserEntity)
        private readonly usersRepository: Repository<UserEntity>
    ) { }

    public create(user) {
        return this.usersRepository.save(getRepository(UserEntity).create(user))
    }
}

執行測試

nest start -w admin

報錯1:

No repository for “UserEntity” was found. Looks like this entity is not registered in current “default” connection

這是typeorm 找不到UserEntity實體,修改db.module.ts

db.module.ts

@Module({
    imports: [
        TypeOrmModule.forRoot({
           ...
            database: 'test',
            entities: [
             UserEntity //這裡改成class
            ],
        })
...

報錯2:

If UserEntityRepository is exported from a separate @Module, is that module imported within UserModule?

userService使用了UserEntity,但是在user.module中沒有import

修改 user.module.ts

@Module({
    imports:[
        TypeOrmModule.forFeature([UserEntity]) //加入這一行
    ],
    providers: [UserService],
    controllers: [UserController]
})
export class UserModule { }

搞定

nestjs monorepo模式

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章