Advertisement
NameL3ss

sparql pagination

Feb 4th, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. class CurrencyQuery
  2. def self.all(search_prefix = nil)
  3. %(
  4. PREFIX dc: <#{PrefixesService::PREFIXES[:dc]}>
  5. PREFIX skos: <#{PrefixesService::PREFIXES[:skos]}>
  6. PREFIX sali: <#{PrefixesService::PREFIXES[:sali]}>
  7. SELECT ?currency ?prefix ?label (REPLACE(?definition, "Locations used: ", "") AS ?cleanedDefinition) ?totalCount
  8. WHERE {
  9. {
  10. SELECT (COUNT(?currency) AS ?totalCount)
  11. WHERE {
  12. ?currency rdfs:subClassOf sali:R767niCLQVC5zIcO5WDQMSl .
  13. ?currency dc:identifier ?prefix .
  14. ?currency rdfs:label ?label .
  15. ?currency skos:definition ?definition .
  16. }
  17. }
  18. ?currency rdfs:subClassOf sali:R767niCLQVC5zIcO5WDQMSl .
  19. ?currency dc:identifier ?prefix .
  20. ?currency rdfs:label ?label .
  21. ?currency skos:definition ?definition .
  22. #{'FILTER(CONTAINS(?prefix, "' + search_prefix.upcase + '"))' if search_prefix.present?}
  23. }
  24. ORDER BY ?prefix
  25. )
  26. end
  27. end
  28.  
  29. def self.all_currencies(search_prefix = nil, page:, per_page:)
  30. sparql_query = CurrencyQuery.all(search_prefix)
  31. sparql_query += "LIMIT #{per_page} OFFSET #{page}"
  32. result = GraphDBConnector.instance.query(sparql_query)
  33. return nil unless result[:success]
  34. return [] unless result[:data].any?
  35.  
  36. [result[:data].first[:totalCount], result[:data]]
  37. end
  38.  
  39. class PaginationService
  40. DEFAULT_PAGE = 1
  41. PER_PAGE = 20
  42. MAX_PER_PAGE = 100
  43.  
  44. def initialize(params)
  45. @page = params[:page].to_i.abs.positive? ? params[:page].to_i.abs : DEFAULT_PAGE
  46. @per_page = validate_per_page(params[:per_page])
  47. end
  48.  
  49. def call
  50. meta = {
  51. page: @page,
  52. per_page: @per_page,
  53. total_elements: nil
  54. }
  55. [@per_page, @page, meta]
  56. end
  57.  
  58. private
  59.  
  60. def validate_per_page(per_page)
  61. per_page = per_page.to_i.abs
  62. per_page = per_page.positive? ? per_page : PER_PAGE
  63. per_page = MAX_PER_PAGE if per_page > MAX_PER_PAGE
  64. per_page
  65. end
  66. end
  67.  
  68. def index
  69. per_page, page, meta = PaginationService.new(page: index_params[:page], per_page: index_params[:per_page]).call
  70. total_elements, records = Amount.all_currencies(index_params[:prefix_search], page: page, per_page: per_page)
  71. meta[:total_elements] = total_elements.value.to_i
  72. render json: CurrencySerializer.new(records: records, root_key: :data, meta: meta).serialized_json, status: :ok
  73. end
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement