Module: QueryInterface::Server::Resource::InstanceMethods

Defined in:
lib/query-interface-server/resource.rb

Instance Method Summary collapse

Instance Method Details

#order_query(order) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/query-interface-server/resource.rb', line 28

def order_query(order)
  order.each do |field|
    direction = :asc
    if field.starts_with?('-')
      field = field[1..-1]
      direction = :desc
    end
    @instances = query_send("order_#{field}_#{direction}") do
      @instances.order_append(Sequel.send(direction, field.to_sym))
    end
  end
end

#queryObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/query-interface-server/resource.rb', line 41

def query
  default_data = {"conditions" => [], "with" => [], "order" => [] }
  if query_data = params[:query_data]
    unless query_data.is_a?(Hash)
      query_data = JSON.parse(query_data)
    end
    query_data = default_data.merge(query_data)

    @instances = query_model.filter.select_all(query_model.table_name)
    query_data["conditions"].each do |key, value|
      @instances = query_send("filter_#{key}", value)
    end

    query_data["with"].each do |field|
      @instances = query_send("with_#{field}")
    end

    order = query_data['order'] << "#{query_model.table_name}__id"
    order_query(order)

    case query_data["mode"].to_sym
    when :evaluate
      @result = @instances
    when :count
      @result = {count: @instances.count}
    when :ids
      id_selector = "#{query_model.table_name}__id".to_sym
      @result = @instances.select(id_selector).map(&:id)
    when :paginate
      page = query_data["page"].to_i
      per_page = query_data["per_page"].to_i
      @result = {total: @instances.count, objects: @instances.paginate(page, per_page)}
    when :first
      @result = @instances.first
    when :last
      @result = @instances.last
    else
      return head :unprocessable_entity
    end
    if @result
      respond_with(@result)
    else
      head :not_found
    end
  else
    head :unprocessable_entity
  end
end

#query_send(method_name, *args) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/query-interface-server/resource.rb', line 16

def query_send(method_name, *args)
  if respond_to?(method_name)
    send(method_name, *args)
  elsif @instances.respond_to?(method_name)
    @instances.send(method_name, *args)
  elsif block_given?
    yield(*args)
  else
    raise Exception, "method #{method_name} not found"
  end
end