NestJS Services 详解:创建和注入服务及管理业务逻辑

服务(Services)是 NestJS 中的核心概念之一,它们用于管理应用程序的业务逻辑。本文将详细介绍 NestJS 中的服务概念,讲解如何创建和注入服务,以及如何通过服务来管理业务逻辑。

服务概述

服务(Services)是用于封装和管理业务逻辑的类。在 NestJS 中,服务通常是通过依赖注入(Dependency Injection)机制来使用的。服务可以被注入到控制器、其他服务或模块中,以提供业务逻辑的复用和分离。

创建服务

在 NestJS 中,创建服务非常简单。我们可以使用 NestJS CLI 来生成服务,也可以手动创建服务。以下是使用 NestJS CLI 创建服务的示例:

Terminal window
1
nest generate service users

上述命令会生成一个 UsersService 文件,我们添加如下内容:

1
import { Injectable } from "@nestjs/common";
2
3
@Injectable()
4
export class UsersService {
5
private readonly users = [];
6
7
findAll() {
8
return this.users;
9
}
10
11
findOne(id: string) {
12
return this.users.find((user) => user.id === id);
13
}
14
15
create(user) {
16
this.users.push(user);
17
}
18
19
update(id: string, user) {
20
const existingUser = this.findOne(id);
21
if (existingUser) {
22
Object.assign(existingUser, user);
23
}
24
}
25
26
remove(id: string) {
27
const index = this.users.findIndex((user) => user.id === id);
28
if (index !== -1) {
29
this.users.splice(index, 1);
30
}
31
}
32
}

在上述示例中,UsersService 是一个带有 @Injectable() 装饰器的类。这个装饰器告诉 NestJS 这个类是一个可注入的服务。

注入服务

在 NestJS 中,服务可以通过依赖注入的方式被注入到控制器或其他服务中。以下是一个将 UsersService 注入到 UsersController 的示例:

1
import {
2
Controller,
3
Get,
4
Post,
5
Put,
6
Delete,
7
Param,
8
Body,
9
} from "@nestjs/common";
10
import { UsersService } from "./users.service";
11
12
@Controller("users")
13
export class UsersController {
14
constructor(private readonly usersService: UsersService) {}
15
16
@Get()
17
findAll() {
18
return this.usersService.findAll();
19
}
20
21
@Get(":id")
22
findOne(@Param("id") id: string) {
23
return this.usersService.findOne(id);
24
}
25
26
@Post()
27
create(@Body() createUserDto: CreateUserDto) {
28
return this.usersService.create(createUserDto);
29
}
30
31
@Put(":id")
32
update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {
33
return this.usersService.update(id, updateUserDto);
34
}
35
36
@Delete(":id")
37
remove(@Param("id") id: string) {
38
return this.usersService.remove(id);
39
}
40
}

在上述示例中,我们在 UsersController 的构造函数中注入了 UsersService。通过这种方式,我们可以在控制器的方法中使用服务提供的业务逻辑。

管理业务逻辑

服务用于封装和管理业务逻辑,将业务逻辑从控制器中分离出来,使代码更加模块化和可维护。以下是一些常见的业务逻辑管理示例:

处理数据存储

服务可以用于处理数据的存储和检索操作,如从数据库中查询数据或保存数据。以下是一个处理用户数据存储的示例:

1
import { Injectable } from "@nestjs/common";
2
import { User } from "./user.entity";
3
4
@Injectable()
5
export class UsersService {
6
private readonly users: User[] = [];
7
8
findAll(): User[] {
9
return this.users;
10
}
11
12
findOne(id: string): User {
13
return this.users.find((user) => user.id === id);
14
}
15
16
create(user: User) {
17
this.users.push(user);
18
}
19
20
update(id: string, user: User) {
21
const existingUser = this.findOne(id);
22
if (existingUser) {
23
Object.assign(existingUser, user);
24
}
25
}
26
27
remove(id: string) {
28
const index = this.users.findIndex((user) => user.id === id);
29
if (index !== -1) {
30
this.users.splice(index, 1);
31
}
32
}
33
}

处理业务规则

服务可以用于处理复杂的业务规则和逻辑,例如计算折扣、验证用户输入等。以下是一个处理用户验证的示例:

1
import { Injectable } from "@nestjs/common";
2
3
@Injectable()
4
export class AuthService {
5
validateUser(username: string, password: string): boolean {
6
// 假设这里有一个用户列表
7
const users = [{ username: "test", password: "password" }];
8
9
const user = users.find(
10
(user) => user.username === username && user.password === password,
11
);
12
return !!user;
13
}
14
}

调用外部API

服务还可以用于调用外部 API,例如通过 HTTP 请求获取数据或与第三方服务进行交互。以下是一个调用外部 API 的示例:

1
import { Injectable, HttpService } from "@nestjs/common";
2
import { map } from "rxjs/operators";
3
4
@Injectable()
5
export class ExternalApiService {
6
constructor(private readonly httpService: HttpService) {}
7
8
fetchData() {
9
return this.httpService
10
.get("https://api.example.com/data")
11
.pipe(map((response) => response.data));
12
}
13
}

总结

本文详细介绍了 NestJS 中的服务(Services)的概念,讲解了如何创建和注入服务,以及如何通过服务来管理业务逻辑。服务在 NestJS 中起到了至关重要的作用,它们用于封装业务逻辑,使代码更加模块化和可维护。

美团外卖红包 饿了么红包 支付宝红包