Don't re-use fat serializers when thin ones are needed.

This cuts the pageload and query count in half, again.
This commit is contained in:
Matt-Yorkley
2020-04-07 14:30:02 +02:00
parent 64c66ddedc
commit 1b7ac1a252
3 changed files with 46 additions and 3 deletions

View File

@@ -74,7 +74,7 @@ module Api
@products = paged_products_for_producers producers
render_paged_products @products
render_paged_products @products, ::Api::Admin::ProductSimpleSerializer
end
# POST /api/products/:product_id/clone
@@ -128,10 +128,10 @@ module Api
page(params[:page]).per(params[:per_page])
end
def render_paged_products(products)
def render_paged_products(products, product_serializer = ::Api::Admin::ProductSerializer)
serializer = ActiveModel::ArraySerializer.new(
products,
each_serializer: ::Api::Admin::ProductSerializer
each_serializer: product_serializer
)
render text: {

View File

@@ -0,0 +1,16 @@
class Api::Admin::ProductSimpleSerializer < ActiveModel::Serializer
attributes :id, :name
has_one :supplier, key: :producer_id, embed: :id
has_many :variants, key: :variants, serializer: Api::Admin::VariantSimpleSerializer
def on_hand
return 0 if object.on_hand.nil?
object.on_hand
end
def price
object.price.nil? ? '0.0' : object.price
end
end

View File

@@ -0,0 +1,27 @@
class Api::Admin::VariantSimpleSerializer < ActiveModel::Serializer
attributes :id, :name, :import_date,
:options_text, :unit_value, :unit_description, :unit_to_display,
:display_as, :display_name, :name_to_display,
:price, :on_demand, :on_hand
has_many :variant_overrides
def name
if object.full_name.present?
"#{object.name} - #{object.full_name}"
else
object.name
end
end
def on_hand
return 0 if object.on_hand.nil?
object.on_hand
end
def price
# Decimals are passed to json as strings, we need to run parseFloat.toFixed(2) on the client.
object.price.nil? ? 0.to_f : object.price
end
end