likes
comments
collection
share

Nest.js入门:高阶JavaScript和TypeScript服务器

作者站长头像
站长
· 阅读数 15

​不要将Nest.js与Next.js混淆,Nest.js是一种较新且独特的JavaScript服务器技术方法。它基于像Express或Fastify这样的熟悉服务器,并添加了许多有用的抽象层,旨在增强和简化更高级别的应用程序设计。由于其独特的编程范式组合、一级TypeScript支持以及内置的依赖注入等功能,Nest.js在过去几年中稳步增长,备受欢迎。

Nest.js是JavaScript生态系统中一项有趣的贡献,值得我们关注。在处理服务器端JavaScript和TypeScript时,它是一个很好的工具。在本文中,我们将快速浏览一下Nest.js,示例包括路由、控制器、生产者(依赖注入)和使用guard进行身份验证。还将了解Nest.js模块系统。我们的示例是一个用于管理意大利面食谱列表的应用程序。我们将包括一个管理实际数据集的依赖注入服务和一个RESTful API,我们可以使用它列出所有食谱或按ID恢复单个食谱。我们还将设置一个简单的经过身份验证的端点,用于添加新食谱。让我们从搭建一个新项目开始。有了这些,我们就可以深入到例子中了。

设置Nest.js演示

我们可以使用Nest.js命令行界面来设置一个快速的应用程序布局,首先要全局安装Nest.js:. 除了命令行界面,还包括一些有用的功能,如用于共享可重用设计的模块。全局安装使我们可以访问这些功能以及更多。现在我们可以使用以下命令创建一个新的应用程序:. 您可以选择任何您想要的包管理器(, , 或 )。对于这个演示,我将使用。无论使用哪个包管理器,过程都是相同的。 切换到新的目录并使用以下命令启动开发服务器:. 您可以通过访问localhost:3000来验证应用程序是否正在运行,您应该会看到一个“Hello, World!”的消息。这个消息来自。如果您查看该文件,您会看到它使用了一个注入的服务。让我们创建一个新的控制器()来返回一个食谱列表,如列表1所示。

列表1:recipe.controller.ts

import { Controller, Get, Inject } from '@nestjs/common';

@Controller('recipes')
export class RecipesController {
  @Get()
  getRecipes() {
    return '[{"name":"Ravioli"}]';
  }
}

使用控制器进行路由处理

列表1向我们展示了Nest.js中路由的基础知识。您可以看到我们使用@Controller注解将类定义为具有路由/recipes的控制器。方法使用@Get()注解来处理GET请求。 目前,这个控制器只是将路由映射到一个硬编码的响应字符串。在Nest.js提供这个功能之前,我们需要在模块中注册新的控制器。模块是Nest中的另一个重要概念,用于帮助组织应用程序代码。在我们的例子中,我们需要打开src/app.module.ts并添加控制器,如列表2所示。

列表2:将新的控制器添加到模块中

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
// Our new controller:
import { RecipesController } from './recipes.controller'; 

@Module({
  imports: [],
  controllers: [AppController,RecipesController],
  providers: [AppService],
})
export class AppModule {}

Nest.js中的依赖注入框架让人想起Java生态系统中的Spring。仅仅拥有内置的依赖注入功能就足以让Nest.js值得考虑,即使没有其他的附加功能。我们将定义一个服务提供者,并将其与我们的控制器连接起来。这是一种将应用程序组织成层次结构的清晰方式。您可以在列表3中看到我们的新服务类RecipesService

列表3:/src/recipes.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class RecipesService {
  private readonly recipes = [
    {
      name: 'Ravioli',
      ingredients: ['pasta', 'cheese', 'tomato sauce'],
    },
    {
      name: 'Lasagna',
      ingredients: ['pasta', 'meat sauce', 'cheese'],
    },
    {
      name: 'Spaghetti',
      ingredients: ['pasta', 'tomato sauce'],
    },
  ];

  getRecipes() {
    return this.recipes;
  }
}

将服务添加到模块中

列表4:将服务添加到模块中

@Module({
  imports: [],
  controllers: [AppController,RecipesController],
  providers: [AppService, RecipesService] // add the service 
})

模块是组织应用程序的一种很好的方式。它们可以作为逻辑分组机制,提供一个层次结构,其中最基本的模块被明确定义,其他模块依赖于它们。

使用服务

现在我们可以在RecipesController中使用服务,如列表5所示。如果您对依赖注入还不熟悉,这可能看起来像是额外的工作量。但是,随着系统的发展,能够以标准化的方式定义和使用类在整个应用程序中是一个真正的优势,对于应用程序架构来说是非常有益的。

列表5:使用RecipesController中的服务

import { Controller, Get, Inject } from '@nestjs/common';
import { RecipesService } from './recipes.service';

@Controller('recipes')
export class RecipesController {
  @Inject()
  private readonly recipesService: RecipesService;
  @Get()
  getRecipes() {
    return this.recipesService.getRecipes();
  }
}

在Nest中,我们首先导入类,然后使用注解在成员上获取对它的引用。注入系统会根据类型将其连接到类的实例上。在Nest中,默认情况下,注入的服务是单例的,因此所有客户端类都会获得对同一个实例的引用。可以使用其他“作用域”来精细调整服务的实例化方式。除了构造函数注入外,Nest还支持基于属性的注入。现在,如果你运行应用程序并访问localhost:3000/recipes,你将看到来自服务中的菜谱数组的JSON输出。

创建POST端点

现在,让我们添加一个新的端点,允许用户添加菜谱。我们将使用Nest.js中称为guard的最简单的身份验证来保护它。Guard位于控制器前面,确定请求的路由方式。您可以在清单6中看到我们简单的guard。目前,它只是检查请求中是否有身份验证头。

列表6:一个简单的AuthGuard

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    // Simple authentication logic
    const request = context.switchToHttp().getRequest();
    const authHeader = request.headers.authorization;
    return authHeader === 'Bearer secret-token';
  }

接下来,向模块注册guard,如清单7所示。

列表7:在app.module.ts中注册这个guard

// ...
import { AuthGuard } from './auth.guard';

@Module({
  imports: [],
  controllers: [AppController, RecipesController],
  providers: [AppService, RecipesService, AuthGuard], 
})
export class AppModule {}

现在我们可以使用新的保护服务来保护端点,如清单8所示。注意新的导入。

列表8:保护POST端点

import { Controller, Get, Inject, Post, Body, UseGuards } from '@nestjs/common';
import { RecipesService } from './recipes.service';
import { AuthGuard } from "./auth.guard";

@Controller('recipes')
export class RecipesController {
  @Inject()
  private readonly recipesService: RecipesService;
  @Get()
  getRecipes() {
    return this.recipesService.getRecipes();
  }
@Post()
  @UseGuards(AuthGuard)
  addRecipe(@Body() recipe: any) {
    return this.recipesService.addRecipe(recipe);
  }
}

请注意,注解被用于将新的guard应用于方法,该方法也被注解指定为一个端点。Nest会负责实例化并将guard应用于端点。我们还在服务中添加了一个非常简单的方法,如清单9所示。

清单9. /src/recipes.service.ts中的addRecipe方法

addRecipe(recipe: any) {
    this.recipes.push(recipe);
    return recipe;
  }

现在我们可以用两个CURL请求测试身份验证和端点,如清单10所示。

列表10:测试新的端点和authguard

$ curl -X POST -H "Authorization: Bearer secret-token" -H "Content-Type: application/json" -d '{"name": "Carbonara", "ingredients": ["pasta", "eggs", "bacon"]}' http://localhost:3000/recipes

{"name":"Carbonara","ingredients":["pasta","eggs","bacon"]}

$ curl -X POST -H "Content-Type: application/json" -d '{"name": "Carbonara", "ingredients": ["pasta", "eggs", "bacon"]}' http://localhost:3000/recipes

{"message":"Forbidden resource","error":"Forbidden","statusCode":403}

可以看到授权正在工作,因为只有持有标头的请求才被允许通过。

在TypeScript中使用Nest

到目前为止,我们只使用了一个JavaScript对象。在TypeScript世界中,通常会创建一个模型对象,并将其用作值对象来传递信息。例如,我们可以创建这个类(列表11)并在方法中使用它(列表12)。

清单11. Recipe模型

export class Recipe {
  constructor(public name: string, public ingredients: string[]) {}

  getName(): string {
    return this.name;
  }

  getIngredients(): string[] {
    return this.ingredients;
  }
}

最后,您可以使该方法具有强类型,Next将自动为我们填充模型对象:addRecipe()POST

列表12:强类型POST方法

import { Injectable } from '@nestjs/common';
import { Recipe } from './recipe.model';

@Injectable()
export class RecipesService {
  private readonly recipes: Recipe[] = [
    new Recipe('Ravioli', ['pasta', 'cheese', 'tomato sauce']),
    new Recipe('Lasagna', ['pasta', 'meat sauce', 'cheese']),
    new Recipe('Spaghetti', ['pasta', 'tomato sauce']),
  ];

  getRecipes(): Recipe[] {
    return this.recipes;
  }

  addRecipe(recipe: Recipe): Recipe {
    this.recipes.push(recipe);
    return recipe;
  }
}

然后,您可以将该方法设置为强类型,Nest将自动为我们填充模型对象,如列表13所示。

列表13:强类型POST方法

// ...
import { Recipe } from './recipe.model';

@Controller('recipes')
export class RecipesController {
  // ...
  @Post()
  @UseGuards(AuthGuard)
  addRecipe(@Body() recipe: Recipe) {
    const newRecipe = new Recipe(recipe.name, recipe.ingredients);
    return this.recipesService.addRecipe(newRecipe);
  }
}

结论

在JavaScript的duck类型和TypeScript的强类型之间的选择,实际上取决于您、团队或组织决定使用什么。JavaScript提供了开发速度和灵活性,而TypeScript提供了结构和更多的工具支持。值得注意的是,Nest.js支持响应式编程,可以从方法和端点返回promises。更重要的是,可以返回一个RxJS Observable。这提供了使用异步数据流将应用程序连接在一起的强大选项。虽然我们只是浅尝辄止,但很明显,Nest.js是一个经过深思熟虑且功能强大的构建Node服务器的平台。它实现了在Express之上提供更好的架构和设计支持的承诺。如果想构建服务器端JavaScript,尤其是TypeScript应用程序,Nest是一个很好的选择。

作者:Matthew Tyson

更多技术干货请关注公众号“云原生数据库

squids.cn,目前可体验全网zui低价RDS,免费的迁移工具DBMotion、SQL开发工具等