search_controller.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class SearchController < ApplicationController
  3. prepend_before_action :authentication_check
  4. # GET|POST /api/v1/search
  5. # GET|POST /api/v1/search/:objects
  6. def search_generic
  7. assets = search_result
  8. .result
  9. .values
  10. .each_with_object({}) { |index_result, memo| ApplicationModel::CanAssets.reduce index_result[:objects], memo }
  11. result = if param_by_object?
  12. result_by_object
  13. else
  14. result_flattened
  15. end
  16. render json: {
  17. assets: assets,
  18. result: result,
  19. }
  20. end
  21. private
  22. def result_by_object
  23. search_result
  24. .result
  25. .each_with_object({}) do |(model, metadata), memo|
  26. memo[model.to_app_model.to_s] = {
  27. object_ids: metadata[:objects].pluck(:id),
  28. total_count: metadata[:total_count]
  29. }
  30. end
  31. end
  32. def result_flattened
  33. search_result
  34. .flattened
  35. .map do |item|
  36. {
  37. type: item.class.to_app_model.to_s,
  38. id: item[:id],
  39. }
  40. end
  41. end
  42. def search_result
  43. @search_result ||= begin
  44. # get params
  45. query = params[:query].try(:permit!)&.to_h || params[:query]
  46. Service::Search
  47. .new(current_user:, query:, objects: search_result_objects, options: search_result_options)
  48. .execute
  49. end
  50. end
  51. def search_result_options
  52. {
  53. limit: params[:limit] || 10,
  54. ids: params[:ids],
  55. offset: params[:offset],
  56. sort_by: Array(params[:sort_by]).compact_blank.presence,
  57. order_by: Array(params[:order_by]).compact_blank.presence,
  58. with_total_count: param_by_object?,
  59. }.compact
  60. end
  61. def param_by_object?
  62. @param_by_object ||= ActiveModel::Type::Boolean.new.cast(params[:by_object])
  63. end
  64. def search_result_objects
  65. objects = Models.searchable
  66. return objects if params[:objects].blank?
  67. given_objects = params[:objects].split('-').map(&:downcase)
  68. objects.select { |elem| given_objects.include? elem.to_app_model.to_s.downcase }
  69. end
  70. end