我正在从头开始一个新的 NestJS 项目。这个项目将有很多 CRUD,我正在尝试找出应用 GET 方法的最佳实践。
据我所知,GET 方法应该只从数据库检索数据(如果需要,则格式化响应,如果在查询参数中指定,则应用过滤器)。这意味着端点(比如说“/primarcs”)必须能够使用相同的 HTTP 方法返回一组数据和一个文档。
假设我在数据库中有下一个模式:
{
"_id": ObjectId,
"name": String
}
显然,我需要一个名为“/primarcs”的端点来返回 BD 的所有文档。该端点还必须能够使用查询参数过滤数据库的数据:Ex:
"/resources" -> Returns all documents of the DB (paginated if needed)
"/resources?name=Fulgrim" -> Returns all documents that matches the name "Fulgrim" (paginated if needed)
当我想要获得一份文件时,我的疑问就会出现。我应该创建一个新端点吗?
/primarcs/{id} -> Where the {id} is the ID of the document I want to get
或者我应该使用现有的 enpoint 并应用查询参数吗?
/primars?_id={id} -> Where the {id} is the ID of the document I want to get
当您考虑应用多个搜索条件时,答案非常简单。
如果您使用路由器参数,您将从
/primarcs
复制相同的处理程序,并对 find 语句的部分进行更改。看起来这没什么大不了的,但想象一下代码有 1000 行。这基本上违反了 DRY 规则(不要重复自己)。
而且,当您需要多个搜索条件时,您会发现这样做
/foo/{id}/{name}
并不是一个好主意。
因此,我建议使用查询参数来应用搜索条件。
type UserSearchQuery = Partial<Record<'id' | 'name', string>>
class App {
@Get()
public async users(@Query() query: UserSearchQuery){
const users = await Users.find({
id: { $eq: query.id ?? null },
name: { $eq: query.name ?? null },
})
return users
}
}
这更容易扩展和管理您的代码。