分页是基于 Fluent 2 分页系统。
将此添加到你的 Package.swift 文件
.package(url: "https://github.com/vapor-community/pagination.git", from: "1.0.0")
使你的模型遵循 Paginatable
extension MyModel: Paginatable { }
一旦你完成之后,就非常简单,只需以分页格式返回你的查询。
func test(_ req: Request) throws -> Future<Paginated<MyModel>> {
return try MyModel.query(on: req).paginate(for: req)
}
甚至可以从查询构建器返回项目
func test(_ req: Request) throws -> Future<Paginated<MyModel>> {
return try MyModel.query(on: req).filter(\MyModel.name == "Test").paginate(for: req)
}
使用参数发起请求非常容易,只需附加 ?page=
和/或 ?per=
curl "https://:8080/api/v1/models?page=1&per=10"
响应看起来像这样
{
"data": [{
"updatedAt": "2018-03-07T00:00:00Z",
"createdAt": "2018-03-07T00:00:00Z",
"name": "My Test Model"
}],
"page": {
"position": {
"current": 1,
"max": 1
},
"data": {
"per": 10,
"total": 2
}
}
}