本文由Notion AI撰写
本文介绍如何使用NestJS框架实现一个支持分页、关键词模糊搜索和选项筛选的商品搜索接口。
实现步骤
1. 安装依赖
首先,我们需要安装一些依赖:
npm install @nestjs/common @nestjs/core @nestjs/platform-express @nestjs/swagger class-validator class-transformer
2. 创建商品实体
我们需要创建一个商品实体,用于描述商品的基本信息。在src
目录下创建一个product.entity.ts
文件,并编写如下代码:
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
export class Product {
@ApiProperty()
@IsNotEmpty()
@IsNumber()
id: number;
@ApiProperty()
@IsNotEmpty()
@IsString()
name: string;
@ApiProperty()
@IsNotEmpty()
@IsNumber()
price: number;
@ApiProperty()
@IsNotEmpty()
@IsString()
description: string;
}
3. 创建商品数据源
我们需要创建一个商品数据源,用于存储商品数据。在src
目录下创建一个product.datasource.ts
文件,并编写如下代码:
import { Injectable } from '@nestjs/common';
import { Product } from './product.entity';
@Injectable()
export class ProductDataSource {
private products: Product[] = [
{ id: 1, name: '商品1', price: 100, description: '这是商品1' },
{ id: 2, name: '商品2', price: 200, description: '这是商品2' },
{ id: 3, name: '商品3', price: 300, description: '这是商品3' },
{ id: 4, name: '商品4', price: 400, description: '这是商品4' },
{ id: 5, name: '商品5', price: 500, description: '这是商品5' },
{ id: 6, name: '商品6', price: 600, description: '这是商品6' },
{ id: 7, name: '商品7', price: 700, description: '这是商品7' },
{ id: 8, name: '商品8', price: 800, description: '这是商品8' },
{ id: 9, name: '商品9', price: 900, description: '这是商品9' },
{ id: 10, name: '商品10', price: 1000, description: '这是商品10' },
];
findAll(): Product[] {
return this.products;
}
}
4. 创建商品服务
我们需要创建一个商品服务,用于处理商品相关的业务逻辑。在src
目录下创建一个product.service.ts
文件,并编写如下代码:
import { Injectable } from '@nestjs/common';
import { Product } from './product.entity';
import { ProductDataSource } from './product.datasource';
@Injectable()
export class ProductService {
constructor(private readonly dataSource: ProductDataSource) {}
findAll(): Product[] {
return this.dataSource.findAll();
}
search(keyword: string, options: any): Product[] {
let products = this.dataSource.findAll();
if (keyword) {
products = products.filter((p) =>
p.name.toLowerCase().includes(keyword.toLowerCase()),
);
}
if (options.minPrice) {
products = products.filter((p) => p.price >= options.minPrice);
}
if (options.maxPrice) {
products = products.filter((p) => p.price <= options.maxPrice);
}
return products;
}
}
5. 创建商品控制器
我们需要创建一个商品控制器,用于处理商品相关的HTTP请求。在src
目录下创建一个product.controller.ts
文件,并编写如下代码:
import { Controller, Get, Query } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
import { Product } from './product.entity';
import { ProductService } from './product.service';
@Controller('products')
@ApiTags('商品')
export class ProductController {
constructor(private readonly service: ProductService) {}
@Get()
@ApiOperation({ summary: '获取商品列表' })
@ApiOkResponse({ type: [Product] })
findAll(): Product[] {
return this.service.findAll();
}
@Get('search')
@ApiOperation({ summary: '搜索商品' })
@ApiOkResponse({ type: [Product] })
@ApiQuery({ name: 'keyword', required: false, description: '关键词' })
@ApiQuery({ name: 'minPrice', required: false, description: '最低价格' })
@ApiQuery({ name: 'maxPrice', required: false, description: '最高价格' })
search(
@Query('keyword') keyword?: string,
@Query('minPrice') minPrice?: number,
@Query('maxPrice') maxPrice?: number,
): Product[] {
const options = { minPrice, maxPrice };
return this.service.search(keyword, options);
}
}
6. 注册商品模块
我们需要将商品相关的组件注册到NestJS的模块中。在src
目录下创建一个product.module.ts
文件,并编写如下代码:
import { Module } from '@nestjs/common';
import { ProductController } from './product.controller';
import { ProductService } from './product.service';
import { ProductDataSource } from './product.datasource';
@Module({
controllers: [ProductController],
providers: [ProductService, ProductDataSource],
})
export class ProductModule {}
7. 启动应用程序
我们需要创建一个main.ts
文件,并编写如下代码:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('商品搜索 API')
.setDescription('商品搜索 API 文档')
.setVersion('1.0')
.addTag('商品')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
await app.listen(3000);
}
bootstrap();
然后我们在命令行中运行npm run start
命令,启动应用程序。
8. 测试接口
现在我们可以使用Postman或者其他HTTP客户端工具测试接口了。
- 获取商品列表:发送GET请求到
http://{host}/products
,应该返回包含所有商品的数组。 - 搜索商品:发送GET请求到
http://{host}/products/search
,可以通过keyword
、minPrice
和maxPrice
参数进行搜索。
总结
本文介绍了如何使用NestJS框架实现一个支持分页、关键词模糊搜索和选项筛选的商品搜索接口。希望对您有所帮助!
本文部分内容包含 AI 辅助创作