Skip to content

Commit

Permalink
Include records on API Order / Product queries
Browse files Browse the repository at this point in the history
When querying for Orders or Products via the API, the significant number
of related records needed to render the JSON for each Order / Product
can lead to a lot of extra database traffic. By using `includes` we can
reduce the query traffic (and thus response time) significantly.
  • Loading branch information
fastjames committed Jan 4, 2019
1 parent 942ec5c commit c2ad54d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 12 additions & 1 deletion api/app/controllers/spree/api/orders_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,18 @@ def empty

def index
authorize! :index, Order
@orders = paginate(Spree::Order.ransack(params[:q]).result)
orders_includes = [
:user,
:payments,
:adjustments,
:line_items
]
@orders = paginate(
Spree::Order
.ransack(params[:q])
.result
.includes(orders_includes)
)
respond_with(@orders)
end

Expand Down
11 changes: 10 additions & 1 deletion api/app/controllers/spree/api/products_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,16 @@ def index
ids = params[:ids].split(",").flatten
@products = product_scope.where(id: ids)
else
@products = product_scope.ransack(params[:q]).result
products_includes = [
:variants,
:option_types,
:product_properties,
{ classifications: :taxon }
]
@products = product_scope
.ransack(params[:q])
.result
.includes(products_includes)
end

@products = paginate(@products.distinct)
Expand Down

0 comments on commit c2ad54d

Please sign in to comment.