Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nestjs #162

Open
yongheng2016 opened this issue May 26, 2023 · 0 comments
Open

nestjs #162

yongheng2016 opened this issue May 26, 2023 · 0 comments

Comments

@yongheng2016
Copy link
Owner

NestJS 是一个用于构建高效、可扩展的 Node.js 服务器端应用程序的框架。它使用 TypeScript 编写(也支持 JavaScript),并结合了 OOP(面向对象编程),FP(函数式编程)和 FRP(函数响应式编程)的元素。

将从基本概念和关键组件开始讲解,然后引导你创建一个简单的 CRUD 项目。让我们开始吧!

安装和创建项目: 首先,确保你的计算机上已经安装了 Node.js 和 npm。然后在命令行中运行以下命令安装 Nest CLI:
npm i -g @nestjs/cli

接下来,使用 Nest CLI 创建一个新项目:

nest new my-nestjs-project

然后进入项目目录:

cd my-nestjs-project
关键概念和组件: NestJS 由一系列组件组成,这有助于开发者在应用程序中保持组织和模块化。主要组件包括:
  • 模块(Modules):用于将相关功能组织在一起。一个 NestJS 应用程序至少有一个根模块(通常命名为 AppModule),其余的模块根据需要组织。
  • 控制器(Controllers):处理传入的 HTTP 请求并返回响应。控制器通过装饰器(如 @get()、@post() 等)将路由映射到函数。
  • 提供者(Providers):可以是服务、存储库、工厂等,它们用于在应用程序中封装和共享业务逻辑或数据访问。
  • 中间件(Middleware):在请求和响应处理过程中起到拦截和转换的作用。例如,处理跨域、验证、日志等。
  • 异常过滤器(Exception Filters):用于捕获和处理应用程序中抛出的错误。
  • 管道(Pipes):用于验证和转换请求数据。
  • 守卫(Guards):用于实现鉴权和授权逻辑。
  • 装饰器(Decorators):自定义的装饰器可以用于增强或修改类、方法或属性。
创建一个简单的 CRUD 项目: 为了让你更好地了解 NestJS 的工作原理,我们将创建一个简单的 CRUD(创建、读取、更新、删除)项目。这里我们假设你要操作一个名为“Item”的实体。
  1. 首先,使用 Nest CLI 自动生成一个模块、控制器和服务:
    nest g module items
    nest g controller items
    nest g service items

2.接下来,打开 items.controller.ts 文件,添加以下代码:

import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common';
import { ItemsService } from './items.service';
import { CreateItemDto } from './dto/create-item.dto';
import { UpdateItemDto } from './dto/update-item.dto';

@Controller('items')
export class ItemsController {
  constructor(private readonly itemsService: ItemsService) {}

  @Get()
  findAll() {
    return this.itemsService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: number) {
    return this.itemsService.findOne(id);
  }

  @Post()
  create(@Body() createItemDto: CreateItemDto) {
    return this.itemsService.create(createItemDto);
  }

  @Put(':id')
  update(@Param('id') id: number, @Body() updateItemDto: UpdateItemDto) {
    return this.itemsService.update(id, updateItemDto);
  }

  @Delete(':id')
  delete(@Param('id') id: number) {
    return this.itemsService.delete(id);
  }
}
  1. 现在,打开 items.service.ts 文件,添加以下实现代码:

    import { Injectable } from '@nestjs/common';
    import { CreateItemDto } from './dto/create-item.dto';
    import { UpdateItemDto } from './dto/update-item.dto';
    
    @Injectable()
    export class ItemsService {
    private items = [];
    
    findAll() {
        return this.items;
    }
    
    findOne(id: number) {
        return this.items.find(item => item.id === id);
    }
    
    create(createItemDto: CreateItemDto) {
        const newItem = { ...createItemDto, id: Date.now() };
        this.items.push(newItem);
        return newItem;
    }
    
    update(id: number, updateItemDto: UpdateItemDto) {
        const itemIndex = this.items.findIndex(item => item.id === id);
        const updatedItem = { ...this.items[itemIndex], ...updateItemDto };
        this.items[itemIndex] = updatedItem;
        return updatedItem;
    }
    
    delete(id: number) {
        const itemIndex = this.items.findIndex(item => item.id === id);
        this.items.splice(itemIndex, 1);
    }
    }
  2. 紧接着,在 items 文件夹中创建两个新文件:create-item.dto.ts 和 update-item.dto.ts,用于定义创建和更新 item 的数据传输对象(DTO):

    create-item.dto.ts 文件内容如下:

    export class CreateItemDto {
    name: string;
    description: string;
    }

    update-item.dto.ts 文件内容如下:

    export class UpdateItemDto {
    name?: string;
    description?: string;
    }
  3. 现在,运行项目:

    npm run start:dev

你将获得一个基本的 CRUD 项目,可以执行以下操作:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant