Git Product home page Git Product logo

jsom-pagination's Introduction

JSOM::Pagination

Gem Version Tests Codacy Badge Codacy Badge

An easy to use JSON:API support for web applications.

Installation

Add this line to your application's Gemfile:

gem 'jsom-pagination'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install jsom-pagination

Usage

For arrays

paginator = JSOM::Pagination::Paginator.new
collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
paginated = paginator.call(collection, params: { number: 2, size: 3 }, base_url: 'https://example.com')

For ActiveRecord collections

paginator = JSOM::Pagination::Paginator.new
collection = Article.published
paginated = paginator.call(collection, params: { number: 2, size: 3 }, base_url: 'https://example.com')

Meta data object

You can call meta on the paginated collection to easily get meta information about the paginated results

paginated.meta
# => #<JSOM::Pagination::MetaData total=10 pages=4>

paginated.meta.to_h
# => {:total=>10, :pages=>4}

Links object

You can call links on the paginated collection to easily get collection of pagination links for the client

paginated.links
# => #<JSOM::Pagination::Links:0x00007fdf5d0dd2b8 @url="https://example.com", @page=#<JSOM::Pagination::Page number=2 size=3>, @total_pages=4, @first="https://example.com?page[size]=3", @prev="https://example.com?page[size]=3", @self="https://example.com?page[number]=2&page[size]=3", @next="https://example.com?page[number]=3&page[size]=3", @last="https://example.com?page[number]=4&page[size]=3">

paginated.links.to_h
# => {
#   :first=>"https://example.com?page[size]=3",
#   :prev=>"https://example.com?page[size]=3",
#   :self=>"https://example.com?page[number]=2&page[size]=3",
#   :next=>"https://example.com?page[number]=3&page[size]=3",
#   :last=>"https://example.com?page[number]=4&page[size]=3"
# }

Rendering using fast_jsonapi

options = { meta: paginated.meta.to_h, links: paginated.links.to_h }
render json: serializer.new(paginated.items, options)

Summary

Using the information above, you can put everything all together by using jsom-pagination in a ruby framework of your choice.

Below is an illustration in Rails:

# app/controllers/concerns/paginable.rb
module Paginable
    extend ActiveSupport::Concern
    
    def paginator
      JSOM::Pagination::Paginator.new
    end
    
    def pagination_params
      params.permit![:page] # defaults to 20 pages 
    end
    
    def paginate(collection)
      paginator.call(collection, params: pagination_params, base_url: request.url)
    end
  
    def render_collection(paginated)
      options = {
        # meta: paginated.meta.to_h, # Will get total pages, total count, etc.
        links: paginated.links.to_h
      }
      paginated_result = serializer.new(paginated.items, options)
  
      render json: paginated_result
    end
end
# app/controllers/articles_controllers.rb
class ArtclesController < ApplicationController
    include Paginable

    def index
        articles = articles = Article.order('created_at DESC')
        paginated = paginate(articles)
    
        articles.present? ? render_collection(paginated) : :not_found
    end

    private

    def serializer
        ArticleSerializer
    end
end

The response from the paginated json will look like below:

{
  "data": [
    {
      "id": "5404329",
      "type": "article",
      "attributes": {
        "author": "Canan Ercan",
        "copies": 10000,
        "publisher": "Webster & Canan Publishers",
        "price": "700"
      }
    }
  ],
  "links": {
    "first": "http://127.0.0.1:3000/api/v1/articles",
    "prev": "http://127.0.0.1:3000/api/v1/articles?page[number]=349",
    "self": "http://127.0.0.1:3000/api/v1/articles?page[number]=350",
    "next": "http://127.0.0.1:3000/api/v1/articles?page[number]=351",
    "last": "http://127.0.0.1:3000/api/v1/articles?page[number]=352"
  }
}

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/useo-pl/jsom-pagination. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the JSOM::Pagination project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

jsom-pagination's People

Contributors

aroeczek avatar avosa avatar codacy-badger avatar intale avatar kbadzioch-u avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

jsom-pagination's Issues

Add Dummy apps to `spec/dummy`

It would be nice to have a real Rails/Hanami/Sinatra applications to be sure everything is working well for all those frameworks and the documentation is valid.

Add Code Quality badges and reports

It would be nice to have badges for code quality, version and passing build

image

Todo

  • Hook up codacy/codeclimate for code quality reporting
  • Add badge for the code quality grade

Add `JSOM::Pagination::Import` to allow injecting dependencies using dry-system

Currently, to get the paginator, we need to instantiate the object in the index class.

paginator = JSOM::Pagination::Paginator.new
paginated = paginator.call(collection, params: { number: 2, size: 3 }, base_ur: 'https://example.com')

It would be nice to instantiate it once during the application boot and allow to reuse the same object whenever it's needed. We could use dry-system for that:

include JSOM::Pagination::Import['paginator']

paginated = paginator.call(collection, params: { number: 2, size: 3 }, base_ur: 'https://example.com')

Add CI using Github actions

Run all our tests automatically using github actions - it would be nice to have also the automatic gem push for rubygems.

References: You can look up for the existing implementation on FastCQRS gem

Arrays As Query Parameters

Hello, thanks for making this gem. It has been really great to use and easy to get up and running.
That being said, I ran into a small issue with the pagination link section when I use arrays as query parameters.

I am making the request: http://localhost:3002/api/recipes?include[]=photo&include[]=nutrition_summary

And getting the return:

}
...
"links": {
    "self": "http://localhost:3002/api/recipes?include=photo=nutrition_summary",
    "next": "http://localhost:3002/api/recipes?include=photo=nutrition_summary&page[number]=2",
    "last": "http://localhost:3002/api/recipes?include=photo=nutrition_summary&page[number]=693"
  }
}

Is there something I am missing from the configuration?

Add Configuration class for default page size

Currently we use Constant to define default page size.

This should be configurable, as when the default page size is requested, it's not included in the links.

Suggested solution:

Add singleton configuration class for JSOM:Pagination

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.