Nest.js项目小结2

时间:2024-04-27 07:43:24

1.配置了项目路径别名

        tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2021",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "paths":{
      "@/*":["src/*"]
    }
  }
}

2.新增了文章功能

        article.controller.ts

import { Controller, Post } from '@nestjs/common'
import { ArticleService } from './article.service'

@Controller()
export class ArticleController{
   constructor(private article: ArticleService) {}

    @Post("article")
    findAll(){
        return this.article.findAll() // 返回的是一个数组
    }
}

        article.module.ts

import { Module } from '@nestjs/common'
import { ArticleController } from './article.controller';
import { ArticleService } from './article.service';

@Module({
   controllers: [ ArticleController],
   providers: [ ArticleService]
})

export class ArticleModule{}

        article.service.ts

import { Injectable } from '@nestjs/common'
import { PrismaService } from '@/prisma/prisma.service'
import { ConfigService } from '@nestjs/config'

@Injectable()
export class ArticleService{
    constructor(private prisma: PrismaService , private config: ConfigService) {}

    async findAll(page = 1) {
        const row = this.config.get('ARTICLE_PAGE_ROW')
        const articles = await this.prisma.article.findMany({
            skip: (page - 1) * row,
            take: +row
        })
        const total = await this.prisma.article.count()


        return {
            meta: {
                current_page: page,
                page_row: row,
                total,
                total_page: Math.ceil(total / row) // 向上取整
            },
            data: articles
        }
    }
}

3.配置了env

DATABASE_URL=

# TOKEN密钥
TOKEN_SECRET = 

# 每页文章数
ARTICLE_PAGE_ROW = 10

4.配置了app.module.ts

import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { PrismaModule } from './prisma/prisma.module';
import { ArticleModule } from './article/article.module';
import { ConfigModule } from '@nestjs/config';


@Module({
  imports: [ AuthModule , PrismaModule , ArticleModule , ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}