项目作者: nodes-vapor

项目描述 :
Offset pagination for Vapor 🗂
高级语言: Swift
项目地址: git://github.com/nodes-vapor/paginator.git
创建时间: 2016-12-23T02:10:03Z
项目社区:https://github.com/nodes-vapor/paginator

开源协议:MIT License

下载


Paginator 🗂

Swift Version
Vapor Version
Circle CI
codebeat badge
codecov
Readme Score
GitHub license

GIF of paginator

This package currently offers support for offset pagination on Array and QueryBuilder.

📦 Installation

Add Paginator to the package dependencies (in your Package.swift file):

  1. dependencies: [
  2. ...,
  3. .package(url: "https://github.com/nodes-vapor/paginator.git", from: "4.0.0")
  4. ]

as well as to your target (e.g. “App”):

  1. targets: [
  2. ...
  3. .target(
  4. name: "App",
  5. dependencies: [... "Paginator" ...]
  6. ),
  7. ...
  8. ]

Next, copy/paste the Resources/Views/Paginator folder into your project in order to be able to use the provided Leaf tags. These files can be changed as explained in the Leaf Tags section, however it’s recommended to copy this folder to your project anyway. This makes it easier for you to keep track of updates and your project will work if you decide later on to not use your own customized leaf files.

Getting started 🚀

First make sure that you’ve imported Paginator everywhere it’s needed:

  1. import Paginator

Adding the Leaf tag

In order to do pagination in Leaf, please make sure to add the Leaf tag:

  1. public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
  2. services.register { _ -> LeafTagConfig in
  3. var tags = LeafTagConfig.default()
  4. tags.use([
  5. "offsetPaginator": OffsetPaginatorTag(templatePath: "Paginator/offsetpaginator")
  6. ])
  7. return tags
  8. }
  9. }

If you want to fully customize the way the pagination control are being generated, you are free to override the template path.

QueryBuilder

To return a paginated result from QueryBuilder, you can do the following:

  1. router.get("galaxies") { (req: Request) -> Future<OffsetPaginator<Galaxy>> in
  2. return Galaxy.query(on: req).paginate(on: req)
  3. }

Array

For convenience, Paginator also comes with support for paginating Array:

  1. router.get("galaxies") { (req: Request) -> Future<OffsetPaginator<Galaxy>> in
  2. let galaxies = [Galaxy(), Galaxy(), Galaxy()]
  3. return galaxies.paginate(on: req)
  4. }

RawSQL

Paginator also comes with support for paginating raw SQL queries for complex expressions not compatible with Fluent.

Simple example using PostgreSQL:

  1. router.get("galaxies") { (req: Request) -> Future<OffsetPaginator<Galaxy>> in
  2. return req.withPooledConnection(to: .psql) { conn -> Future<OffsetPaginator<Galaxy>> in
  3. let rawBuilder = RawSQLBuilder<PostgreSQLDatabase, Galaxy>(
  4. query: """
  5. SELECT *
  6. FROM public."Galaxy"
  7. """, countQuery: """
  8. SELECT COUNT(*) as "count"
  9. FROM public."Galaxy"
  10. """, connection: conn)
  11. return try rawBuilder.paginate(on: req)
  12. }
  13. }

Note: the count query is expected to have a result with one column named count and with the total columns value in the first row

Leaf tags

To use Paginator together with Leaf, you can do the following:

  1. struct GalaxyList: Codable {
  2. let galaxies: [Galaxy]
  3. }
  4. router.get("galaxies") { (req: Request) -> Response in
  5. let paginator: Future<OffsetPaginator<Galaxy>> = Galaxy.query(on: req).paginate(on: req)
  6. return paginator.flatMap(to: Response.self) { paginator in
  7. return try req.view().render(
  8. "MyLeafFile",
  9. GalaxyList(galaxies: paginator.data ?? []),
  10. userInfo: try paginator.userInfo(),
  11. on: req
  12. )
  13. .encode(for: req)
  14. }
  15. }

Please note how the Paginator data is being passed in using userInfo on the render call. Forgetting to pass this in will result in an error being thrown.

Then in your MyLeafFile.leaf you could do something like:

  1. <ul>
  2. #for(galaxy in galaxies) {
  3. <li>#(galaxy.name)</li>
  4. }
  5. </ul>
  6. #offsetPaginator()

Calling the Leaf tag for OffsetPaginator will automatically generate the Bootstrap 4 HTML for showing the pagination controls:

  1. <nav class="paginator">
  2. <ul class="pagination justify-content-center table-responsive">
  3. <li class="page-item">
  4. <a href="/admin/users?page=16" class="page-link" rel="prev" aria-label="Previous">
  5. <span aria-hidden="true">«</span>
  6. <span class="sr-only">Previous</span>
  7. </a>
  8. </li>
  9. <li class="page-item "><a href="/admin/users?page=1" class="page-link">1</a></li>
  10. <li class="disabled page-item"><a href="#" class="page-link">...</a></li>
  11. <li class="page-item "><a href="" class="page-link">12</a></li>
  12. <li class="page-item "><a href="" class="page-link">13</a></li>
  13. <li class="page-item "><a href="" class="page-link">14</a></li>
  14. <li class="page-item "><a href="" class="page-link">15</a></li>
  15. <li class="page-item "><a href="" class="page-link">16</a></li>
  16. <li class="page-item active "><a href="" class="page-link">17</a></li>
  17. <li class="page-item "><a href="/admin/users?page=18" class="page-link">18</a></li>
  18. <li class="page-item">
  19. <a href="/admin/users?page=18" class="page-link" rel="next" aria-label="Next">
  20. <span aria-hidden="true">»</span>
  21. <span class="sr-only">Next</span>
  22. </a>
  23. </li>
  24. </ul>
  25. </nav>

Transforming

The data in an OffsetPaginator can be transformed by mapping over the paginator and transforming each element at a time:

  1. Galaxy.query(on: req).paginate(on: req).map { paginator in
  2. paginator.map { (galaxy: Galaxy) -> GalaxyViewModel in
  3. GalaxyViewModel(galaxy: galaxy)
  4. }
  5. }

You can also transform a whole page of results at once:

  1. Galaxy.query(on: req).paginate(on: req).map { paginator in
  2. paginator.map { (galaxies: [Galaxy]) -> [GalaxyViewModel] in
  3. galaxies.map(GalaxyViewModel.init)
  4. }
  5. }

In case the transformation requires async work you can do:

  1. Galaxy.query(on: req).paginate(on: req).map { paginator in
  2. paginator.flatMap { (galaxies: [Galaxy]) -> Future<[GalaxyViewModel]> in
  3. galaxies.someAsyncMethod()
  4. }
  5. }

Configuration

The OffsetPaginator has a configuration file (OffsetPaginatorConfig) that can be overwritten if needed. This can be done in configure.swift:

  1. public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
  2. // ..
  3. services.register(OffsetPaginatorConfig(
  4. perPage: 1,
  5. defaultPage: 1
  6. ))
  7. }

🏆 Credits

This package is developed and maintained by the Vapor team at Nodes.

📄 License

This package is open-sourced software licensed under the MIT license