返回

用 NestJS 搭建博客系统 — 创建项目并添加功能

前端

搭建框架

使用 NestJS 搭建博客系统的第一章,我们先了解一下 NestJS 这个框架,然后创建一个新的 NestJS 项目。

什么是 NestJS?

NestJS 是一个构建高效、可扩展的 Node.js 应用程序的框架。它基于 TypeScript,并遵循面向对象的设计原则。NestJS 提供了一系列特性,包括:

  • 模块化架构:NestJS 采用模块化架构,可以将应用程序拆分为多个独立的模块,方便代码管理和维护。
  • 注解驱动:NestJS 使用注解来装饰类和方法,以定义它们的用途和行为。这使得 NestJS 应用程序的代码更加简洁和易于理解。
  • 内置中间件:NestJS 提供了一系列内置中间件,可以用来处理请求和响应、验证数据、以及处理错误。
  • 测试支持:NestJS 提供了完善的测试支持,方便开发人员编写单元测试和集成测试。

创建一个新的 NestJS 项目

要创建一个新的 NestJS 项目,我们可以使用 NestJS CLI 工具。首先,确保已安装 Node.js 和 npm。然后,在命令行中输入以下命令:

nest new my-blog

这将在当前目录中创建一个名为 my-blog 的新 NestJS 项目。

进入项目目录,运行以下命令安装依赖项:

npm install

运行以下命令启动开发服务器:

npm run start:dev

现在,你可以访问 http://localhost:3000 来查看你的博客系统。

添加功能

在这一步,我们将添加一些基本的功能到我们的博客系统中。

添加文章

首先,我们需要创建一个文章的模型。在 src/app/article/article.model.ts 文件中,添加以下代码:

export class Article {
  id: number;
  title: string;
  content: string;
  author: string;
  createdAt: Date;
  updatedAt: Date;
}

接下来,我们需要创建一个文章的服务。在 src/app/article/article.service.ts 文件中,添加以下代码:

import { Injectable } from '@nestjs/common';
import { Article } from './article.model';

@Injectable()
export class ArticleService {
  private articles: Article[] = [];

  getAll(): Article[] {
    return this.articles;
  }

  get(id: number): Article {
    return this.articles.find(article => article.id === id);
  }

  create(article: Article): void {
    this.articles.push(article);
  }

  update(article: Article): void {
    const index = this.articles.findIndex(article => article.id === article.id);
    this.articles[index] = article;
  }

  delete(id: number): void {
    const index = this.articles.findIndex(article => article.id === id);
    this.articles.splice(index, 1);
  }
}

最后,我们需要创建一个文章的控制器。在 src/app/article/article.controller.ts 文件中,添加以下代码:

import { Controller, Get, Post, Body, Param, Delete, Patch } from '@nestjs/common';
import { ArticleService } from './article.service';
import { Article } from './article.model';

@Controller('articles')
export class ArticleController {
  constructor(private readonly articleService: ArticleService) {}

  @Get()
  getAll(): Article[] {
    return this.articleService.getAll();
  }

  @Get(':id')
  get(@Param('id') id: string): Article {
    return this.articleService.get(parseInt(id));
  }

  @Post()
  create(@Body() article: Article): void {
    this.articleService.create(article);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() article: Article): void {
    this.articleService.update(article);
  }

  @Delete(':id')
  delete(@Param('id') id: string): void {
    this.articleService.delete(parseInt(id));
  }
}

现在,我们就可以在浏览器中访问 http://localhost:3000/articles 来查看所有的文章,也可以访问 http://localhost:3000/articles/1 来查看具体的一篇文章。

下一步

在本系列的下一章中,我们将介绍如何连接数据库,以便我们可以持久化我们的文章数据。