Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Switch to Alba for serialization, added `ar_lazy_preload` and implemented HTTP caching

Damian Legawiec9653e45b69f3
diff --git a/api/app/controllers/concerns/spree/api/v3/expandable_resources.rb b/api/app/controllers/concerns/spree/api/v3/expandable_resources.rb
deleted file mode 100644
index 920d37a226..0000000000
--- a/api/app/controllers/concerns/spree/api/v3/expandable_resources.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-module Spree
- module Api
- module V3
- # Provides support for expanding nested resources in serializers
- # Similar to Stripe's expand parameter: https://docs.stripe.com/api/expanding_objects
- #
- # Usage:
- # GET /api/v3/storefront/products/1?include=variants,images,taxons
- # GET /api/v3/storefront/products/1?include=variants.images,variants.option_values
- module ExpandableResources
- extend ActiveSupport::Concern
-
- protected
-
- # Returns list of associations to include based on query params
- # @return [Array<String>] List of associations to expand
- def requested_includes
- return [] unless params[:include].present?
-
- # Split by comma, remove whitespace
- params[:include].to_s.split(',').map(&:strip).reject(&:blank?)
- end
-
- # Check if a specific association should be included
- # @param association [String, Symbol] The association name
- # @return [Boolean]
- def include?(association)
- requested_includes.include?(association.to_s)
- end
-
- # Get nested includes for an association
- # For example, if params[:include] = 'variants.images,variants.option_values'
- # Then nested_includes_for('variants') returns ['images', 'option_values']
- #
- # @param parent [String, Symbol] The parent association
- # @return [Array<String>]
- def nested_includes_for(parent)
- prefix = "#{parent}."
- requested_includes
- .select { |inc| inc.start_with?(prefix) }
- .map { |inc| inc.sub(prefix, '') }
- end
- end
- end
- end
-end
diff --git a/api/app/controllers/concerns/spree/api/v3/http_caching.rb b/api/app/controllers/concerns/spree/api/v3/http_caching.rb
new file mode 100644
index 0000000000..d080002a71
--- /dev/null
+++ b/api/app/controllers/concerns/spree/api/v3/http_caching.rb
@@ -0,0 +1,89 @@
+module Spree
+ module Api
+ module V3
+ # Provides HTTP caching support for API v3 controllers
+ #
+ # Strategy:
+ # - Guest users: Public HTTP caching with CDN support (5-15 min TTL)
+ # - Authenticated users: Private, no-store (no caching)
+ #
+ # Uses ETag and Last-Modified headers for cache validation.
+ module HttpCaching
+ extend ActiveSupport::Concern
+
+ included do
+ before_action :set_vary_headers
+ end
+
+ protected
+
+ # Check if the current user is a guest (no authentication)
+ def guest_user?
+ current_user.nil? || current_user.try(:guest?)
+ end
+
+ # Set Vary headers to ensure proper CDN caching by currency/locale
+ def set_vary_headers
+ if guest_user?
+ response.headers['Vary'] = 'Accept, X-Spree-Currency, X-Spree-Locale'
+ else
+ response.headers['Cache-Control'] = 'private, no-store'
+ end
+ end
+
+ # Apply HTTP caching for a collection (index actions)
+ # Only caches for guest users
+ #
+ # @param collection [ActiveRecord::Relation] The collection to cache
+ # @param expires_in [ActiveSupport::Duration] Cache TTL (default: 5 minutes)
+ # @param stale_while_revalidate [ActiveSupport::Duration] Allow stale responses while revalidating
+ # @return [Boolean] true if response should be rendered, false if 304 Not Modified
+ def cache_collection(collection, expires_in: 5.minutes, stale_while_revalidate: 30.seconds)
+ return true unless guest_user?
+
+ expires_in expires_in, public: true, stale_while_revalidate: stale_while_revalidate
+
+ # Use collection's cache key for ETag
+ cache_key = collection_cache_key(collection)
+ response.headers['ETag'] = %("#{Digest::MD5.hexdigest(cache_key)}")
+
+ # Return false if client has fresh cache (304 Not Modified)
+ !request.fresh?(response)
+ end
+
+ # Apply HTTP caching for a single resource (show actions)
+ # Only caches for guest users
+ #
+ # @param resource [ActiveRecord::Base] The resource to cache
+ # @param expires_in [ActiveSupport::Duration] Cache TTL (default: 5 minutes)
+ # @return [Boolean] true if response should be rendered, false if 304 Not Modified
+ def cache_resource(resource, expires_in: 5.minutes)
+ return true unless guest_user?
+
+ expires_in expires_in, public: true
+
+ # Use Rails' stale? which handles ETag and Last-Modified
+ stale?(resource, public: true)
+ end
+
+ private
+
+ # Build a cache key for a collection
+ # Includes: query params, pagination, includes, currency, locale
+ def collection_cache_key(collection)
+ parts = [
+ collection.cache_key_with_version,
+ params[:include],
+ params[:q],
+ params[:page],
+ params[:per_page],
+ current_currency,
+ current_locale
+ ]
+
+ parts.compact.join('/')
+ end
+ end
+ end
+ end
+end
diff --git a/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb b/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb
index 026e27628a..402983ca67 100644
--- a/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb
+++ b/api/app/controllers/concerns/spree/api/v3/resource_serializer.rb
@@ -8,12 +8,31 @@ module Spree
# Serialize a single resource
def serialize_resource(resource)
- serializer_class.new(resource, serializer_context).as_json
+ serializer_class.new(resource, params: serializer_params).to_h
end
# Serialize a collection of resources
def serialize_collection(collection)
- collection.map { |item| serializer_class.new(item, serializer_context).as_json }
+ collection.map { |item| serializer_class.new(item, params: serializer_params).to_h }
+ end
+
+ # Params passed to serializers
+ def serializer_params
+ {
+ currency: current_currency,
+ store: current_store,
+ user: current_user,
+ locale: current_locale,
+ includes: include_list
+ }
+ end
+
+ # Parse include parameter into list
+ # Supports: ?include=variants,images or ?include=variants.images
+ def include_list
+ return [] unless params[:include].present?
+
+ params[:include].to_s.split(',').map(&:strip)
end
end
end
diff --git a/api/app/controllers/spree/api/v3/base_controller.rb b/api/app/controllers/spree/api/v3/base_controller.rb
index 3fb53f82f8..ff7d9ed5b1 100644
--- a/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/api/app/controllers/spree/api/v3/base_controller.rb
@@ -9,8 +9,8 @@ module Spree
include Spree::Core::ControllerHelpers::Locale
include Spree::Core::ControllerHelpers::Currency
include Spree::Api::V3::Authentication
- include Spree::Api::V3::ExpandableResources
include Spree::Api::V3::ErrorHandler
+ include Spree::Api::V3::HttpCaching
# Optional authentication by default
before_action :authenticate_user
diff --git a/api/app/controllers/spree/api/v3/resource_controller.rb b/api/app/controllers/spree/api/v3/resource_controller.rb
index 2b16a6e10b..1c18eb9ebf 100644
--- a/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -11,6 +11,9 @@ module Spree
def index
@collection = collection
+ # Apply HTTP caching for guests
+ return unless cache_collection(@collection)
+
render json: {
data: serialize_collection(@collection),
meta: collection_meta(@collection)
@@ -19,6 +22,9 @@ module Spree
# GET /api/v3/resource/:id
def show
+ # Apply HTTP caching for guests
+ return unless cache_resource(@resource)
+
render json: serialize_resource(@resource)
end
@@ -63,14 +69,15 @@ module Spree
end
# Returns ransack-filtered, sorted and paginated collection
+ # ar_lazy_preload handles automatic association preloading
# @return [ActiveRecord::Relation]
def collection
return @collection if @collection.present?
@search = scope.ransack(ransack_params)
result = @search.result(distinct: true)
- @pagy, records = pagy(result, limit: limit, page: page)
- records
+ @pagy, @collection = pagy(result, limit: limit, page: page)
+ @collection
end
# Ransack query parameters
@@ -105,7 +112,7 @@ module Spree
}
end
- # Base scope with store, ability, and includes
+ # Base scope with store and ability
def scope
base_scope = model_class.for_store(current_store)
base_scope = base_scope.accessible_by(current_ability, :show)
@@ -113,7 +120,8 @@ module Spree
model_class.include?(Spree::TranslatableResource) ? base_scope.i18n : base_scope
end
- # Override in subclass to eager load associations
+ # Override in subclass to eager load associations that don't work well
+ # with ar_lazy_preload (e.g., prices, stock_items)
def scope_includes
[]
end
@@ -123,7 +131,7 @@ module Spree
raise NotImplementedError, 'Subclass must implement model_class'
end
- # Override in subclass to define the serializer
+ # Override in subclass to define the serializer class
def serializer_class
raise NotImplementedError, 'Subclass must implement serializer_class'
end
@@ -132,17 +140,6 @@ module Spree
def permitted_params
raise NotImplementedError, 'Subclass must implement permitted_params'
end
-
- # Context passed to serializers
- def serializer_context
- {
- currency: current_currency,
- store: current_store,
- user: current_user,
- locale: current_locale,
- includes: requested_includes
- }
- end
end
end
end
diff --git a/api/app/controllers/spree/api/v3/storefront/addresses_controller.rb b/api/app/controllers/spree/api/v3/storefront/addresses_controller.rb
index 372acac24a..4c550e2932 100644
--- a/api/app/controllers/spree/api/v3/storefront/addresses_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/addresses_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_address_serializer.constantize
+ Spree.api.v3_storefront_address_serializer
end
def permitted_params
diff --git a/api/app/controllers/spree/api/v3/storefront/auth_controller.rb b/api/app/controllers/spree/api/v3/storefront/auth_controller.rb
index 336a86b77a..71b2b3a713 100644
--- a/api/app/controllers/spree/api/v3/storefront/auth_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/auth_controller.rb
@@ -24,7 +24,7 @@ module Spree
token = generate_jwt(user)
render json: {
token: token,
- user: user_serializer.new(user, serializer_context).as_json
+ user: user_serializer.new(user, params: serializer_params).to_h
}
else
render_error(
@@ -43,7 +43,7 @@ module Spree
token = generate_jwt(user)
render json: {
token: token,
- user: user_serializer.new(user, serializer_context).as_json
+ user: user_serializer.new(user, params: serializer_params).to_h
}, status: :created
else
render_errors(user.errors)
@@ -55,7 +55,7 @@ module Spree
token = generate_jwt(current_user)
render json: {
token: token,
- user: user_serializer.new(current_user, serializer_context).as_json
+ user: user_serializer.new(current_user, params: serializer_params).to_h
}
end
@@ -77,7 +77,7 @@ module Spree
token = generate_jwt(user)
render json: {
token: token,
- user: user_serializer.new(user, serializer_context).as_json
+ user: user_serializer.new(user, params: serializer_params).to_h
}
else
render_error(
@@ -90,10 +90,13 @@ module Spree
protected
- def serializer_context
+ def serializer_params
{
store: current_store,
- locale: current_locale
+ locale: current_locale,
+ currency: current_currency,
+ user: current_user,
+ includes: []
}
end
@@ -132,7 +135,7 @@ module Spree
end
def user_serializer
- Spree::Api::Dependencies.v3_storefront_user_serializer.constantize
+ Spree.api.v3_storefront_user_serializer
end
end
end
diff --git a/api/app/controllers/spree/api/v3/storefront/countries_controller.rb b/api/app/controllers/spree/api/v3/storefront/countries_controller.rb
index e5524ddfaf..1fc31501e0 100644
--- a/api/app/controllers/spree/api/v3/storefront/countries_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/countries_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_country_serializer.constantize
+ Spree.api.v3_storefront_country_serializer
end
# Not needed for index/show
diff --git a/api/app/controllers/spree/api/v3/storefront/coupon_codes_controller.rb b/api/app/controllers/spree/api/v3/storefront/coupon_codes_controller.rb
index 8ae44f0791..26c420190a 100644
--- a/api/app/controllers/spree/api/v3/storefront/coupon_codes_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/coupon_codes_controller.rb
@@ -33,14 +33,10 @@ module Spree
protected
def serialize_order
- serializer_class.new(@order, serializer_context).as_json
+ serializer_class.new(@order, params: serializer_params).to_h
end
- def serializer_class
- Spree::Api::Dependencies.v3_storefront_order_serializer.constantize
- end
-
- def serializer_context
+ def serializer_params
{
currency: current_currency,
store: current_store,
diff --git a/api/app/controllers/spree/api/v3/storefront/customers_controller.rb b/api/app/controllers/spree/api/v3/storefront/customers_controller.rb
index efd4689f46..753dafc666 100644
--- a/api/app/controllers/spree/api/v3/storefront/customers_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/customers_controller.rb
@@ -22,18 +22,18 @@ module Spree
protected
def serialize_resource(resource)
- serializer_class.new(resource, serializer_context).as_json
+ serializer_class.new(resource, params: serializer_params).to_h
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_user_serializer.constantize
+ Spree.api.v3_storefront_user_serializer
end
- def serializer_context
+ def serializer_params
{
store: current_store,
locale: current_locale,
- includes: requested_includes
+ includes: include_tree
}
end
diff --git a/api/app/controllers/spree/api/v3/storefront/line_items_controller.rb b/api/app/controllers/spree/api/v3/storefront/line_items_controller.rb
index 83553865bf..6ca6e4899e 100644
--- a/api/app/controllers/spree/api/v3/storefront/line_items_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/line_items_controller.rb
@@ -83,7 +83,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_line_item_serializer.constantize
+ Spree.api.v3_storefront_line_item_serializer
end
def permitted_params
diff --git a/api/app/controllers/spree/api/v3/storefront/order_addresses_controller.rb b/api/app/controllers/spree/api/v3/storefront/order_addresses_controller.rb
index 0d246a5f00..1e75e005c2 100644
--- a/api/app/controllers/spree/api/v3/storefront/order_addresses_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/order_addresses_controller.rb
@@ -52,17 +52,18 @@ module Spree
end
def serialize_address(address)
- serializer_class.new(address, serializer_context).as_json
+ serializer_class.new(address, params: serializer_params).to_h
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_address_serializer.constantize
+ Spree.api.v3_storefront_address_serializer
end
- def serializer_context
+ def serializer_params
{
store: current_store,
- locale: current_locale
+ locale: current_locale,
+ includes: include_tree
}
end
diff --git a/api/app/controllers/spree/api/v3/storefront/orders_controller.rb b/api/app/controllers/spree/api/v3/storefront/orders_controller.rb
index 1cc116647a..a48f796700 100644
--- a/api/app/controllers/spree/api/v3/storefront/orders_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/orders_controller.rb
@@ -106,7 +106,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_order_serializer.constantize
+ Spree.api.v3_storefront_order_serializer
end
def permitted_params
diff --git a/api/app/controllers/spree/api/v3/storefront/pages_controller.rb b/api/app/controllers/spree/api/v3/storefront/pages_controller.rb
deleted file mode 100644
index cba651d178..0000000000
--- a/api/app/controllers/spree/api/v3/storefront/pages_controller.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-module Spree
- module Api
- module V3
- module Storefront
- class PagesController < ResourceController
- # Public endpoint - no authentication required
-
- protected
-
- def scope
- super.without_previews.where(pageable: current_store)
- end
-
- def model_class
- Spree::Page
- end
-
- def serializer_class
- Spree::Api::Dependencies.v3_storefront_page_serializer.constantize
- end
-
- # Not needed for index/show
- def permitted_params
- {}
- end
- end
- end
- end
- end
-end
diff --git a/api/app/controllers/spree/api/v3/storefront/payment_methods_controller.rb b/api/app/controllers/spree/api/v3/storefront/payment_methods_controller.rb
index e8564925fd..f3c5218fbf 100644
--- a/api/app/controllers/spree/api/v3/storefront/payment_methods_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/payment_methods_controller.rb
@@ -24,19 +24,19 @@ module Spree
end
def serialize_collection(collection)
- collection.map { |item| serializer_class.new(item, serializer_context).as_json }
+ collection.map { |item| serializer_class.new(item, params: serializer_params).to_h }
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_payment_method_serializer.constantize
+ Spree.api.v3_storefront_payment_method_serializer
end
- def serializer_context
+ def serializer_params
{
currency: current_currency,
store: current_store,
locale: current_locale,
- includes: requested_includes
+ includes: include_tree
}
end
end
diff --git a/api/app/controllers/spree/api/v3/storefront/payment_sources_controller.rb b/api/app/controllers/spree/api/v3/storefront/payment_sources_controller.rb
index ca8cd1f4ab..b071ee09b6 100644
--- a/api/app/controllers/spree/api/v3/storefront/payment_sources_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/payment_sources_controller.rb
@@ -33,39 +33,17 @@ module Spree
end
def serialize_collection(collection)
- collection.map { |item| serializer_class.new(item, serializer_context).as_json }
+ collection.map { |item| serialize_resource(item) }
end
def serialize_resource(resource)
- serializer_class.new(resource, serializer_context).as_json
- end
-
- def serializer_class
- # Using a simple inline serializer for credit cards to avoid exposing sensitive data
- Class.new do
- attr_reader :resource
-
- def initialize(resource, context = {})
- @resource = resource
- end
-
- def as_json
- {
- id: resource.id,
- cc_type: resource.cc_type,
- last_digits: resource.last_digits,
- month: resource.month,
- year: resource.year,
- name: resource.name
- }
- end
- end
- end
-
- def serializer_context
{
- store: current_store,
- locale: current_locale
+ id: resource.id,
+ cc_type: resource.cc_type,
+ last_digits: resource.last_digits,
+ month: resource.month,
+ year: resource.year,
+ name: resource.name
}
end
end
diff --git a/api/app/controllers/spree/api/v3/storefront/payments_controller.rb b/api/app/controllers/spree/api/v3/storefront/payments_controller.rb
index 0f678d20c9..15698f5f0c 100644
--- a/api/app/controllers/spree/api/v3/storefront/payments_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/payments_controller.rb
@@ -44,7 +44,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_payment_serializer.constantize
+ Spree.api.v3_storefront_payment_serializer
end
def permitted_params
diff --git a/api/app/controllers/spree/api/v3/storefront/policies_controller.rb b/api/app/controllers/spree/api/v3/storefront/policies_controller.rb
deleted file mode 100644
index 1ad851f76f..0000000000
--- a/api/app/controllers/spree/api/v3/storefront/policies_controller.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-module Spree
- module Api
- module V3
- module Storefront
- class PoliciesController < ResourceController
- # Public endpoint - no authentication required
-
- protected
-
- def scope
- Spree::Policy.active.for_store(current_store).accessible_by(current_ability, :show)
- end
-
- def model_class
- Spree::Policy
- end
-
- def serializer_class
- # Simple inline serializer for policies
- Class.new do
- attr_reader :resource
-
- def initialize(resource, context = {})
- @resource = resource
- end
-
- def as_json
- {
- id: resource.id,
- title: resource.title,
- slug: resource.slug,
- content: resource.content,
- created_at: resource.created_at,
- updated_at: resource.updated_at
- }
- end
- end
- end
-
- # Not needed for index/show
- def permitted_params
- {}
- end
- end
- end
- end
- end
-end
diff --git a/api/app/controllers/spree/api/v3/storefront/posts_controller.rb b/api/app/controllers/spree/api/v3/storefront/posts_controller.rb
index c0328c532a..78e2facfa1 100644
--- a/api/app/controllers/spree/api/v3/storefront/posts_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/posts_controller.rb
@@ -15,14 +15,12 @@ module Spree
Spree::Post
end
- def serializer_class
# Simple inline serializer for posts
Class.new do
attr_reader :resource
def initialize(resource, context = {})
@resource = resource
- end
def as_json
{
diff --git a/api/app/controllers/spree/api/v3/storefront/products_controller.rb b/api/app/controllers/spree/api/v3/storefront/products_controller.rb
index 08a19816c9..4a6fdbffa0 100644
--- a/api/app/controllers/spree/api/v3/storefront/products_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/products_controller.rb
@@ -3,8 +3,6 @@ module Spree
module V3
module Storefront
class ProductsController < ResourceController
- include Spree::Api::V2::ProductListIncludes
-
protected
def model_class
@@ -12,7 +10,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_product_serializer.constantize
+ Spree.api.v3_storefront_product_serializer
end
def scope
@@ -21,18 +19,8 @@ module Spree
def scope_includes
[
- :prices_including_master,
- :variant_images,
- :option_types,
- :option_values,
- :taxons,
- { taggings: [:tag] },
- { master: [:images, :prices, :stock_items, :stock_locations, { stock_items: :stock_location }],
- variants: [
- :images, :prices, :option_values, :stock_items, :stock_locations,
- { option_values: :option_type, stock_items: :stock_location }
- ],
- }
+ master: [:prices, { stock_items: :stock_location }],
+ variants: [:prices, {option_values: :option_type }, { stock_items: :stock_location }]
]
end
diff --git a/api/app/controllers/spree/api/v3/storefront/sections_controller.rb b/api/app/controllers/spree/api/v3/storefront/sections_controller.rb
deleted file mode 100644
index 45b3a5205f..0000000000
--- a/api/app/controllers/spree/api/v3/storefront/sections_controller.rb
+++ /dev/null
@@ -1,52 +0,0 @@
-module Spree
- module Api
- module V3
- module Storefront
- class SectionsController < BaseController
- before_action :set_page
-
- # GET /api/v3/storefront/pages/:page_id/sections
- def index
- @sections = @page.sections.ordered
-
- render json: {
- data: serialize_collection(@sections)
- }
- end
-
- # GET /api/v3/storefront/pages/:page_id/sections/:id
- def show
- @section = @page.sections.find(params[:id])
- render json: serialize_resource(@section)
- end
-
- protected
-
- def set_page
- @page = Spree::Page.visible.for_store(current_store).find(params[:page_id])
- end
-
- def serialize_collection(collection)
- collection.map { |item| serializer_class.new(item, serializer_context).as_json }
- end
-
- def serialize_resource(resource)
- serializer_class.new(resource, serializer_context).as_json
- end
-
- def serializer_class
- Spree::Api::Dependencies.v3_storefront_section_serializer.constantize
- end
-
- def serializer_context
- {
- store: current_store,
- locale: current_locale,
- includes: requested_includes
- }
- end
- end
- end
- end
- end
-end
diff --git a/api/app/controllers/spree/api/v3/storefront/shipments_controller.rb b/api/app/controllers/spree/api/v3/storefront/shipments_controller.rb
index 698e68f7bd..685861a5af 100644
--- a/api/app/controllers/spree/api/v3/storefront/shipments_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/shipments_controller.rb
@@ -42,7 +42,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_shipment_serializer.constantize
+ Spree.api.v3_storefront_shipment_serializer
end
def permitted_params
diff --git a/api/app/controllers/spree/api/v3/storefront/shipping_methods_controller.rb b/api/app/controllers/spree/api/v3/storefront/shipping_methods_controller.rb
index 4037fbc2f1..a0f0dd51d2 100644
--- a/api/app/controllers/spree/api/v3/storefront/shipping_methods_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/shipping_methods_controller.rb
@@ -24,19 +24,19 @@ module Spree
end
def serialize_collection(collection)
- collection.map { |item| serializer_class.new(item, serializer_context).as_json }
+ collection.map { |item| serializer_class.new(item, params: serializer_params).to_h }
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_shipping_method_serializer.constantize
+ Spree.api.v3_storefront_shipping_method_serializer
end
- def serializer_context
+ def serializer_params
{
currency: current_currency,
store: current_store,
locale: current_locale,
- includes: requested_includes
+ includes: include_tree
}
end
end
diff --git a/api/app/controllers/spree/api/v3/storefront/states_controller.rb b/api/app/controllers/spree/api/v3/storefront/states_controller.rb
index 043aaa87c8..7897852702 100644
--- a/api/app/controllers/spree/api/v3/storefront/states_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/states_controller.rb
@@ -23,7 +23,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_state_serializer.constantize
+ Spree.api.v3_storefront_state_serializer
end
# Not needed for index/show
diff --git a/api/app/controllers/spree/api/v3/storefront/stores_controller.rb b/api/app/controllers/spree/api/v3/storefront/stores_controller.rb
index da99bae4ee..8b166edd3b 100644
--- a/api/app/controllers/spree/api/v3/storefront/stores_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/stores_controller.rb
@@ -24,7 +24,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_store_serializer.constantize
+ Spree.api.v3_storefront_store_serializer
end
# Not needed for show
diff --git a/api/app/controllers/spree/api/v3/storefront/taxons_controller.rb b/api/app/controllers/spree/api/v3/storefront/taxons_controller.rb
index 4605d9ca0b..1197b8f9d0 100644
--- a/api/app/controllers/spree/api/v3/storefront/taxons_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/taxons_controller.rb
@@ -12,17 +12,11 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_taxon_serializer.constantize
+ Spree.api.v3_storefront_taxon_serializer
end
def scope
- Spree::Taxon
- .for_store(current_store)
- .includes(scope_includes)
- end
-
- def scope_includes
- [:taxonomy, :parent, :children]
+ Spree::Taxon.for_store(current_store)
end
# Not needed for index/show
diff --git a/api/app/controllers/spree/api/v3/storefront/variants_controller.rb b/api/app/controllers/spree/api/v3/storefront/variants_controller.rb
index b3ded9d9ee..30ae52f6b0 100644
--- a/api/app/controllers/spree/api/v3/storefront/variants_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/variants_controller.rb
@@ -18,16 +18,11 @@ module Spree
end
def scope
- @product.variants
- .accessible_by(current_ability, :show)
- .includes(scope_includes)
+ @product.variants.accessible_by(current_ability, :show).includes(scope_includes)
end
def scope_includes
- [
- :images, :prices, :option_values, :stock_items, :stock_locations,
- { option_values: :option_type, stock_items: :stock_location }
- ]
+ [:prices, { stock_items: :stock_location }]
end
def model_class
@@ -35,7 +30,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_variant_serializer.constantize
+ Spree.api.v3_storefront_variant_serializer
end
# Not needed for index/show
diff --git a/api/app/controllers/spree/api/v3/storefront/wishlist_items_controller.rb b/api/app/controllers/spree/api/v3/storefront/wishlist_items_controller.rb
index 9b9519283d..dc2273ad40 100644
--- a/api/app/controllers/spree/api/v3/storefront/wishlist_items_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/wishlist_items_controller.rb
@@ -59,7 +59,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_wished_item_serializer.constantize
+ Spree.api.v3_storefront_wished_item_serializer
end
def permitted_params
@@ -69,14 +69,6 @@ module Spree
def item_params
params.require(:item).permit(Spree::PermittedAttributes.wished_item_attributes)
end
-
- def serialize_collection(collection)
- collection.map { |item| serializer_class.new(item, serializer_context).as_json }
- end
-
- def serialize_resource(resource)
- serializer_class.new(resource, serializer_context).as_json
- end
end
end
end
diff --git a/api/app/controllers/spree/api/v3/storefront/wishlists_controller.rb b/api/app/controllers/spree/api/v3/storefront/wishlists_controller.rb
index 47d780a782..a2adb96538 100644
--- a/api/app/controllers/spree/api/v3/storefront/wishlists_controller.rb
+++ b/api/app/controllers/spree/api/v3/storefront/wishlists_controller.rb
@@ -27,7 +27,7 @@ module Spree
end
def serializer_class
- Spree::Api::Dependencies.v3_storefront_wishlist_serializer.constantize
+ Spree.api.v3_storefront_wishlist_serializer
end
def permitted_params
diff --git a/api/app/serializers/spree/api/v3/address_serializer.rb b/api/app/serializers/spree/api/v3/address_serializer.rb
index f93c67cce3..50231d1fff 100644
--- a/api/app/serializers/spree/api/v3/address_serializer.rb
+++ b/api/app/serializers/spree/api/v3/address_serializer.rb
@@ -2,27 +2,17 @@ module Spree
module Api
module V3
class AddressSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- firstname: resource.firstname,
- lastname: resource.lastname,
- full_name: resource.full_name,
- address1: resource.address1,
- address2: resource.address2,
- city: resource.city,
- zipcode: resource.zipcode,
- phone: resource.phone,
- company: resource.company,
- state_id: resource.state_id,
- state_name: resource.state_name,
- state_text: resource.state_text,
- country_id: resource.country_id,
- country_name: resource.country&.name,
- country_iso: resource.country&.iso,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :firstname, :lastname, :full_name, :address1, :address2,
+ :city, :zipcode, :phone, :company, :state_id, :state_name,
+ :state_text, :country_id,
+ created_at: :iso8601, updated_at: :iso8601
+
+ attribute :country_name do |address|
+ address.country&.name
+ end
+
+ attribute :country_iso do |address|
+ address.country&.iso
end
end
end
diff --git a/api/app/serializers/spree/api/v3/base_serializer.rb b/api/app/serializers/spree/api/v3/base_serializer.rb
index 211ba8f835..fad6026bd9 100644
--- a/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -2,102 +2,61 @@ module Spree
module Api
module V3
class BaseSerializer
- attr_reader :resource, :context, :includes
+ include Alba::Resource
- def initialize(resource, context = {})
- @resource = resource
- @context = context
- @includes = Array(context[:includes] || [])
+ # Context accessors
+ def current_store
+ params[:store]
end
- # Main serialization method
- def as_json
- attributes
+ def current_currency
+ params[:currency]
end
- protected
-
- # Override in subclasses to define attributes
- def attributes
- {
- id: resource.id
- }
- end
-
- # Check if an association should be included
- # @param association [String, Symbol] The association name
- # @return [Boolean]
- def include?(association)
- includes.include?(association.to_s)
- end
-
- # Get nested includes for a parent association
- # @param parent [String, Symbol] The parent association
- # @return [Array<String>]
- def nested_includes_for(parent)
- prefix = "#{parent}."
- includes
- .select { |inc| inc.start_with?(prefix) }
- .map { |inc| inc.sub(prefix, '') }
- end
-
- # Context for nested serializers
- # @param parent [String, Symbol] The parent association name
- # @return [Hash]
- def nested_context(parent = nil)
- ctx = context.dup
- ctx[:includes] = parent ? nested_includes_for(parent) : []
- ctx
- end
-
- # Context helpers
- def currency
- context[:currency]
+ def current_user
+ params[:user]
end
- def store
- context[:store]
+ def current_locale
+ params[:locale]
end
- def user
- context[:user]
+ def includes
+ @includes ||= Array(params[:includes] || [])
end
- def locale
- context[:locale]
+ # Check if an association should be included
+ def include?(name)
+ includes.include?(name.to_s)
end
- # Price helpers
- def money_to_hash(money)
- return nil unless money
-
- {
- amount: money.to_f,
- currency: money.currency.iso_code,
- formatted: money.to_s
- }
+ # Get nested includes for a given parent
+ def nested_includes_for(parent)
+ prefix = "#{parent}."
+ includes.select { |i| i.start_with?(prefix) }.map { |i| i.sub(prefix, '') }
end
- def price_in_currency(priceable)
- return nil unless priceable.respond_to?(:price_in)
-
- priceable.price_in(currency)
+ # Build nested params for child serializers
+ def nested_params(parent = nil)
+ params.merge(includes: parent ? nested_includes_for(parent) : [])
end
- # Image URL helper
- def image_url(image, size: nil)
- return nil unless image&.attached?
+ # Returns price for a variant using full Price List resolution
+ def price_for(variant, quantity: nil)
+ return nil unless variant.respond_to?(:price_for)
- url_helpers.cdn_image_url(image.attachment)
+ variant.price_for(
+ currency: current_currency,
+ store: current_store,
+ user: current_user,
+ quantity: quantity
+ )
end
- def url_helpers
- Rails.application.routes.url_helpers
- end
+ def image_url_for(image)
+ return nil unless image&.attachment&.attached?
- # Timestamp helper
- def timestamp(time)
- time&.iso8601
+ Rails.application.routes.url_helpers.cdn_image_url(image.attachment)
end
end
end
diff --git a/api/app/serializers/spree/api/v3/country_serializer.rb b/api/app/serializers/spree/api/v3/country_serializer.rb
index f936d9a9d1..acc8d4ca0b 100644
--- a/api/app/serializers/spree/api/v3/country_serializer.rb
+++ b/api/app/serializers/spree/api/v3/country_serializer.rb
@@ -2,35 +2,11 @@ module Spree
module Api
module V3
class CountrySerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- iso: resource.iso,
- iso3: resource.iso3,
- iso_name: resource.iso_name,
- name: resource.name,
- states_required: resource.states_required,
- zipcode_required: resource.zipcode_required
- }
+ attributes :id, :iso, :iso3, :iso_name, :name, :states_required, :zipcode_required
- # Conditionally include states
- base_attrs[:states] = serialize_states if include?('states')
-
- base_attrs
- end
-
- private
-
- def serialize_states
- resource.states.map do |state|
- state_serializer.new(state, nested_context('states')).as_json
- end
- end
-
- # Serializer dependencies
- def state_serializer
- Spree::Api::Dependencies.v3_storefront_state_serializer.constantize
- end
+ many :states,
+ resource: Spree.api.v3_storefront_state_serializer,
+ if: proc { params[:includes]&.include?('states') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/image_serializer.rb b/api/app/serializers/spree/api/v3/image_serializer.rb
index 09eac27151..f81fc5539a 100644
--- a/api/app/serializers/spree/api/v3/image_serializer.rb
+++ b/api/app/serializers/spree/api/v3/image_serializer.rb
@@ -2,17 +2,42 @@ module Spree
module Api
module V3
class ImageSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- position: resource.position,
- alt: resource.alt,
- original_url: image_url(resource),
- large_url: image_url(resource, size: [1200, 1200]),
- medium_url: image_url(resource, size: [600, 600]),
- small_url: image_url(resource, size: [300, 300]),
- thumbnail_url: image_url(resource, size: [150, 150])
- }
+ attributes :id, :position, :alt
+
+ attribute :original_url do |image|
+ image_url(image)
+ end
+
+ attribute :large_url do |image|
+ image_url(image, size: [1200, 1200])
+ end
+
+ attribute :medium_url do |image|
+ image_url(image, size: [600, 600])
+ end
+
+ attribute :small_url do |image|
+ image_url(image, size: [300, 300])
+ end
+
+ attribute :thumbnail_url do |image|
+ image_url(image, size: [150, 150])
+ end
+
+ private
+
+ def image_url(image, size: nil)
+ unless image&.attachment&.attached?
+ return nil
+ end
+
+ if size
+ Rails.application.routes.url_helpers.cdn_image_url(
+ image.attachment.variant(resize_to_limit: size)
+ )
+ else
+ Rails.application.routes.url_helpers.cdn_image_url(image.attachment)
+ end
end
end
end
diff --git a/api/app/serializers/spree/api/v3/line_item_serializer.rb b/api/app/serializers/spree/api/v3/line_item_serializer.rb
index 0436b38fad..3bdcba039e 100644
--- a/api/app/serializers/spree/api/v3/line_item_serializer.rb
+++ b/api/app/serializers/spree/api/v3/line_item_serializer.rb
@@ -2,59 +2,84 @@ module Spree
module Api
module V3
class LineItemSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- quantity: resource.quantity,
- price: resource.price.to_f,
- display_price: resource.display_price.to_s,
+ attributes :id, :quantity, :name, :slug, :options_text, :currency
- total: resource.total.to_f,
- display_total: resource.display_total.to_s,
+ attribute :price do |line_item|
+ line_item.price.to_f
+ end
+
+ attribute :display_price do |line_item|
+ line_item.display_price.to_s
+ end
+
+ attribute :total do |line_item|
+ line_item.total.to_f
+ end
- adjustment_total: resource.adjustment_total.to_f,
- display_adjustment_total: resource.display_adjustment_total.to_s,
+ attribute :display_total do |line_item|
+ line_item.display_total.to_s
+ end
+
+ attribute :adjustment_total do |line_item|
+ line_item.adjustment_total.to_f
+ end
+
+ attribute :display_adjustment_total do |line_item|
+ line_item.display_adjustment_total.to_s
+ end
- promo_total: resource.promo_total.to_f,
- display_promo_total: resource.display_promo_total.to_s,
+ attribute :promo_total do |line_item|
+ line_item.promo_total.to_f
+ end
- included_tax_total: resource.included_tax_total.to_f,
- display_included_tax_total: resource.display_included_tax_total.to_s,
+ attribute :display_promo_total do |line_item|
+ line_item.display_promo_total.to_s
+ end
- additional_tax_total: resource.additional_tax_total.to_f,
- display_additional_tax_total: resource.display_additional_tax_total.to_s,
+ attribute :included_tax_total do |line_item|
+ line_item.included_tax_total.to_f
+ end
- pre_tax_amount: resource.pre_tax_amount.to_f,
- display_pre_tax_amount: resource.display_pre_tax_amount.to_s,
+ attribute :display_included_tax_total do |line_item|
+ line_item.display_included_tax_total.to_s
+ end
- compare_at_amount: resource.compare_at_amount.to_f,
- display_compare_at_amount: resource.display_compare_at_amount.to_s,
+ attribute :additional_tax_total do |line_item|
+ line_item.additional_tax_total.to_f
+ end
- discounted_amount: resource.discounted_amount.to_f,
- display_discounted_amount: resource.display_discounted_amount.to_s,
+ attribute :display_additional_tax_total do |line_item|
+ line_item.display_additional_tax_total.to_s
+ end
- name: resource.name,
- slug: resource.slug,
- options_text: resource.options_text,
- currency: resource.currency
- }
+ attribute :pre_tax_amount do |line_item|
+ line_item.pre_tax_amount.to_f
+ end
- # Conditionally include variant
- base_attrs[:variant] = serialize_variant if include?('variant')
+ attribute :display_pre_tax_amount do |line_item|
+ line_item.display_pre_tax_amount.to_s
+ end
- base_attrs
+ attribute :compare_at_amount do |line_item|
+ line_item.compare_at_amount.to_f
end
- private
+ attribute :display_compare_at_amount do |line_item|
+ line_item.display_compare_at_amount.to_s
+ end
- def serialize_variant
- variant_serializer.new(resource.variant, nested_context('variant')).as_json if resource.variant
+ attribute :discounted_amount do |line_item|
+ line_item.discounted_amount.to_f
end
- # Serializer dependencies
- def variant_serializer
- Spree::Api::Dependencies.v3_storefront_variant_serializer.constantize
+ attribute :display_discounted_amount do |line_item|
+ line_item.display_discounted_amount.to_s
end
+
+ # Conditional associations
+ one :variant,
+ resource: Spree.api.v3_storefront_variant_serializer,
+ if: proc { params[:includes]&.include?('variant') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/option_type_serializer.rb b/api/app/serializers/spree/api/v3/option_type_serializer.rb
index 4323e649e8..d525be1751 100644
--- a/api/app/serializers/spree/api/v3/option_type_serializer.rb
+++ b/api/app/serializers/spree/api/v3/option_type_serializer.rb
@@ -2,32 +2,11 @@ module Spree
module Api
module V3
class OptionTypeSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- name: resource.name,
- presentation: resource.presentation,
- position: resource.position
- }
+ attributes :id, :name, :presentation, :position
- # Conditionally include option_values
- base_attrs[:option_values] = serialize_option_values if include?('option_values')
-
- base_attrs
- end
-
- private
-
- def serialize_option_values
- resource.option_values.map do |option_value|
- option_value_serializer.new(option_value, nested_context('option_values')).as_json
- end
- end
-
- # Serializer dependencies
- def option_value_serializer
- Spree::Api::Dependencies.v3_storefront_option_value_serializer.constantize
- end
+ many :option_values,
+ resource: Spree.api.v3_storefront_option_value_serializer,
+ if: proc { params[:includes]&.include?('option_values') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/option_value_serializer.rb b/api/app/serializers/spree/api/v3/option_value_serializer.rb
index 5c375f0355..fa6d7aca61 100644
--- a/api/app/serializers/spree/api/v3/option_value_serializer.rb
+++ b/api/app/serializers/spree/api/v3/option_value_serializer.rb
@@ -2,15 +2,10 @@ module Spree
module Api
module V3
class OptionValueSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- presentation: resource.presentation,
- position: resource.position,
- option_type_id: resource.option_type_id,
- option_type_name: resource.option_type.name
- }
+ attributes :id, :name, :presentation, :position, :option_type_id
+
+ attribute :option_type_name do |option_value|
+ option_value.option_type.name
end
end
end
diff --git a/api/app/serializers/spree/api/v3/order_serializer.rb b/api/app/serializers/spree/api/v3/order_serializer.rb
index 0f1c2d32c2..cac1ed89fa 100644
--- a/api/app/serializers/spree/api/v3/order_serializer.rb
+++ b/api/app/serializers/spree/api/v3/order_serializer.rb
@@ -2,105 +2,104 @@ module Spree
module Api
module V3
class OrderSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- number: resource.number,
- state: resource.state,
- token: resource.token,
- email: resource.email,
- special_instructions: resource.special_instructions,
- currency: resource.currency,
- item_count: resource.item_count,
+ attributes :id, :number, :state, :token, :email, :special_instructions,
+ :currency, :item_count, :shipment_state, :payment_state
- # Totals
- item_total: resource.item_total.to_f,
- display_item_total: resource.display_item_total.to_s,
-
- ship_total: resource.ship_total.to_f,
- display_ship_total: resource.display_ship_total.to_s,
-
- adjustment_total: resource.adjustment_total.to_f,
- display_adjustment_total: resource.display_adjustment_total.to_s,
-
- promo_total: resource.promo_total.to_f,
- display_promo_total: resource.display_promo_total.to_s,
+ # Totals
+ attribute :item_total do |order|
+ order.item_total.to_f
+ end
- tax_total: resource.tax_total.to_f,
- display_tax_total: resource.display_tax_total.to_s,
+ attribute :display_item_total do |order|
+ order.display_item_total.to_s
+ end
- included_tax_total: resource.included_tax_total.to_f,
- display_included_tax_total: resource.display_included_tax_total.to_s,
+ attribute :ship_total do |order|
+ order.ship_total.to_f
+ end
- additional_tax_total: resource.additional_tax_total.to_f,
- display_additional_tax_total: resource.display_additional_tax_total.to_s,
+ attribute :display_ship_total do |order|
+ order.display_ship_total.to_s
+ end
- total: resource.total.to_f,
- display_total: resource.display_total.to_s,
+ attribute :adjustment_total do |order|
+ order.adjustment_total.to_f
+ end
- # States
- shipment_state: resource.shipment_state,
- payment_state: resource.payment_state,
+ attribute :display_adjustment_total do |order|
+ order.display_adjustment_total.to_s
+ end
- # Timestamps
- completed_at: timestamp(resource.completed_at),
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attribute :promo_total do |order|
+ order.promo_total.to_f
+ end
- # Conditionally include associations
- base_attrs[:line_items] = serialize_line_items if include?('line_items')
- base_attrs[:payments] = serialize_payments if include?('payments')
- base_attrs[:shipments] = serialize_shipments if include?('shipments')
- base_attrs[:billing_address] = serialize_billing_address if include?('billing_address')
- base_attrs[:shipping_address] = serialize_shipping_address if include?('shipping_address')
+ attribute :display_promo_total do |order|
+ order.display_promo_total.to_s
+ end
- base_attrs
+ attribute :tax_total do |order|
+ order.tax_total.to_f
end
- private
+ attribute :display_tax_total do |order|
+ order.display_tax_total.to_s
+ end
- def serialize_line_items
- resource.line_items.map do |line_item|
- line_item_serializer.new(line_item, nested_context('line_items')).as_json
- end
+ attribute :included_tax_total do |order|
+ order.included_tax_total.to_f
end
- def serialize_payments
- resource.payments.valid.map do |payment|
- payment_serializer.new(payment, nested_context('payments')).as_json
- end
+ attribute :display_included_tax_total do |order|
+ order.display_included_tax_total.to_s
end
- def serialize_shipments
- resource.shipments.map do |shipment|
- shipment_serializer.new(shipment, nested_context('shipments')).as_json
- end
+ attribute :additional_tax_total do |order|
+ order.additional_tax_total.to_f
end
- def serialize_billing_address
- address_serializer.new(resource.bill_address, nested_context('billing_address')).as_json if resource.bill_address
+ attribute :display_additional_tax_total do |order|
+ order.display_additional_tax_total.to_s
end
- def serialize_shipping_address
- address_serializer.new(resource.ship_address, nested_context('shipping_address')).as_json if resource.ship_address
+ attribute :total do |order|
+ order.total.to_f
end
- # Serializer dependencies
- def line_item_serializer
- Spree::Api::Dependencies.v3_storefront_line_item_serializer.constantize
+ attribute :display_total do |order|
+ order.display_total.to_s
end
- def payment_serializer
- Spree::Api::Dependencies.v3_storefront_payment_serializer.constantize
+ # Timestamps
+ attributes completed_at: :iso8601, created_at: :iso8601, updated_at: :iso8601
+
+ # Conditional associations
+ many :line_items,
+ resource: Spree.api.v3_storefront_line_item_serializer,
+ if: proc { params[:includes]&.include?('line_items') }
+
+ many :shipments,
+ resource: Spree.api.v3_storefront_shipment_serializer,
+ if: proc { params[:includes]&.include?('shipments') }
+
+ many :payments,
+ resource: Spree.api.v3_storefront_payment_serializer,
+ if: proc { params[:includes]&.include?('payments') } do |order|
+ order.payments.valid
end
- def shipment_serializer
- Spree::Api::Dependencies.v3_storefront_shipment_serializer.constantize
+ one :billing_address,
+ key: :billing_address,
+ resource: Spree.api.v3_storefront_address_serializer,
+ if: proc { params[:includes]&.include?('billing_address') } do |order|
+ order.bill_address
end
- def address_serializer
- Spree::Api::Dependencies.v3_storefront_address_serializer.constantize
+ one :shipping_address,
+ key: :shipping_address,
+ resource: Spree.api.v3_storefront_address_serializer,
+ if: proc { params[:includes]&.include?('shipping_address') } do |order|
+ order.ship_address
end
end
end
diff --git a/api/app/serializers/spree/api/v3/payment_method_serializer.rb b/api/app/serializers/spree/api/v3/payment_method_serializer.rb
index 38c77b77c9..2092057a43 100644
--- a/api/app/serializers/spree/api/v3/payment_method_serializer.rb
+++ b/api/app/serializers/spree/api/v3/payment_method_serializer.rb
@@ -2,17 +2,8 @@ module Spree
module Api
module V3
class PaymentMethodSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- description: resource.description,
- type: resource.type,
- active: resource.active,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
- end
+ attributes :id, :name, :description, :type, :active,
+ created_at: :iso8601, updated_at: :iso8601
end
end
end
diff --git a/api/app/serializers/spree/api/v3/payment_serializer.rb b/api/app/serializers/spree/api/v3/payment_serializer.rb
index 7f16e1a284..da1284f7c4 100644
--- a/api/app/serializers/spree/api/v3/payment_serializer.rb
+++ b/api/app/serializers/spree/api/v3/payment_serializer.rb
@@ -2,21 +2,20 @@ module Spree
module Api
module V3
class PaymentSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- amount: resource.amount.to_f,
- display_amount: resource.display_amount.to_s,
- state: resource.state,
- payment_method_id: resource.payment_method_id,
- payment_method_name: resource.payment_method&.name,
- response_code: resource.response_code,
- number: resource.number,
- cvv_response_code: resource.cvv_response_code,
- cvv_response_message: resource.cvv_response_message,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :state, :payment_method_id, :response_code, :number,
+ :cvv_response_code, :cvv_response_message,
+ created_at: :iso8601, updated_at: :iso8601
+
+ attribute :amount do |payment|
+ payment.amount.to_f
+ end
+
+ attribute :display_amount do |payment|
+ payment.display_amount.to_s
+ end
+
+ attribute :payment_method_name do |payment|
+ payment.payment_method&.name
end
end
end
diff --git a/api/app/serializers/spree/api/v3/product_serializer.rb b/api/app/serializers/spree/api/v3/product_serializer.rb
index 8ef6f4fead..13f6000a2d 100644
--- a/api/app/serializers/spree/api/v3/product_serializer.rb
+++ b/api/app/serializers/spree/api/v3/product_serializer.rb
@@ -2,113 +2,89 @@ module Spree
module Api
module V3
class ProductSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- name: resource.name,
- description: resource.description,
- slug: resource.slug,
- sku: resource.sku,
- barcode: resource.barcode,
- available_on: timestamp(resource.available_on),
- meta_description: resource.meta_description,
- meta_keywords: resource.meta_keywords,
- purchasable: resource.purchasable?,
- in_stock: resource.in_stock?,
- backorderable: resource.backorderable?,
- available: resource.available?,
- currency: currency,
- price: price_value,
- display_price: display_price_value,
- compare_at_price: compare_at_price_value,
- display_compare_at_price: display_compare_at_price_value,
- tags: resource.taggings.map(&:tag),
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
-
- # Conditionally include associations based on include parameter
- base_attrs[:images] = serialize_images if include?('images')
- base_attrs[:variants] = serialize_variants if include?('variants')
- base_attrs[:default_variant] = serialize_default_variant if include?('default_variant')
- base_attrs[:master_variant] = serialize_master_variant if include?('master_variant')
- base_attrs[:option_types] = serialize_option_types if include?('option_types')
- base_attrs[:taxons] = serialize_taxons if include?('taxons')
-
- base_attrs
- end
-
- private
+ attributes :id, :name, :description, :slug, :sku, :barcode,
+ :meta_description, :meta_keywords,
+ available_on: :iso8601, created_at: :iso8601, updated_at: :iso8601
- def price_value
- price = price_in_currency(resource)
- price&.amount&.to_f
+ attribute :purchasable do |product|
+ product.purchasable?
end
- def display_price_value
- price = price_in_currency(resource)
- price&.display_price&.to_s
+ attribute :in_stock do |product|
+ product.in_stock?
end
- def compare_at_price_value
- price = price_in_currency(resource)
- price&.compare_at_amount&.to_f
+ attribute :backorderable do |product|
+ product.backorderable?
end
- def display_compare_at_price_value
- price = price_in_currency(resource)
- return nil unless price&.compare_at_amount
-
- Spree::Money.new(price.compare_at_amount, currency: currency).to_s
+ attribute :available do |product|
+ product.available?
end
- def serialize_images
- resource.variant_images.map do |image|
- image_serializer.new(image, nested_context('images')).as_json
- end
+ attribute :price do |product|
+ price_object(product)&.amount&.to_f
end
- def serialize_variants
- resource.variants.map do |variant|
- variant_serializer.new(variant, nested_context('variants')).as_json
- end
+ attribute :price_in_cents do |product|
+ price_object(product)&.display_amount&.amount_in_cents
end
- def serialize_default_variant
- variant_serializer.new(resource.default_variant, nested_context('default_variant')).as_json if resource.default_variant
+ attribute :display_price do |product|
+ price_object(product)&.display_price&.to_s
end
- def serialize_master_variant
- variant_serializer.new(resource.master, nested_context('master_variant')).as_json if resource.master
+ attribute :compare_at_price do |product|
+ price_object(product)&.compare_at_amount&.to_f
end
- def serialize_option_types
- resource.option_types.map do |option_type|
- option_type_serializer.new(option_type, nested_context('option_types')).as_json
- end
+ attribute :compare_at_price_in_cents do |product|
+ price_object(product)&.display_compare_at_amount&.amount_in_cents if price_object(product)&.compare_at_amount&.present?
end
- def serialize_taxons
- resource.taxons_for_store(store).map do |taxon|
- taxon_serializer.new(taxon, nested_context('taxons')).as_json
- end
+ attribute :display_compare_at_price do |product|
+ price_object(product)&.display_compare_at_amount&.to_s if price_object(product)&.compare_at_amount&.present?
end
- # Serializer dependencies
- def image_serializer
- Spree::Api::Dependencies.v3_storefront_image_serializer.constantize
+ attribute :tags do |product|
+ product.taggings.map(&:tag)
end
- def variant_serializer
- Spree::Api::Dependencies.v3_storefront_variant_serializer.constantize
- end
+ # Conditional associations
+ many :images,
+ resource: Spree.api.v3_storefront_image_serializer,
+ if: proc { params[:includes]&.include?('images') },
+ source: :variant_images
+
+ many :variants,
+ resource: Spree.api.v3_storefront_variant_serializer,
+ if: proc { params[:includes]&.include?('variants') }
+
+ one :default_variant,
+ resource: Spree.api.v3_storefront_variant_serializer,
+ if: proc { params[:includes]&.include?('default_variant') }
+
+ one :master_variant,
+ key: :master_variant,
+ resource: Spree.api.v3_storefront_variant_serializer,
+ if: proc { params[:includes]&.include?('master_variant') },
+ source: :master
+
+ many :option_types,
+ resource: Spree.api.v3_storefront_option_type_serializer,
+ if: proc { params[:includes]&.include?('option_types') }
+
+ many :taxons,
+ proc { |taxons, params|
+ taxons.select { |t| t.taxonomy.store_id == params[:store].id}
+ },
+ resource: Spree.api.v3_storefront_taxon_serializer,
+ if: proc { params[:includes]&.include?('taxons') }
- def option_type_serializer
- Spree::Api::Dependencies.v3_storefront_option_type_serializer.constantize
- end
+ private
- def taxon_serializer
- Spree::Api::Dependencies.v3_storefront_taxon_serializer.constantize
+ def price_object(product)
+ @price_object ||= price_for(product.default_variant)
end
end
end
diff --git a/api/app/serializers/spree/api/v3/shipment_serializer.rb b/api/app/serializers/spree/api/v3/shipment_serializer.rb
index aeb954da7e..7bfc50f771 100644
--- a/api/app/serializers/spree/api/v3/shipment_serializer.rb
+++ b/api/app/serializers/spree/api/v3/shipment_serializer.rb
@@ -2,58 +2,39 @@ module Spree
module Api
module V3
class ShipmentSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- number: resource.number,
- state: resource.state,
- tracking: resource.tracking,
- cost: resource.cost.to_f,
- display_cost: resource.display_cost.to_s,
- shipped_at: timestamp(resource.shipped_at),
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at),
- shipping_method: serialize_shipping_method,
- stock_location: serialize_stock_location
- }
-
- # Conditionally include associations
- base_attrs[:shipping_rates] = serialize_shipping_rates if include?('shipping_rates')
+ attributes :id, :number, :state, :tracking,
+ shipped_at: :iso8601, created_at: :iso8601, updated_at: :iso8601
- base_attrs
+ attribute :cost do |shipment|
+ shipment.cost.to_f
end
- private
+ attribute :display_cost do |shipment|
+ shipment.display_cost.to_s
+ end
- def serialize_shipping_method
- return unless resource.shipping_method
+ attribute :shipping_method do |shipment|
+ next unless shipment.shipping_method
{
- id: resource.shipping_method.id,
- name: resource.shipping_method.name,
- code: resource.shipping_method.code
+ id: shipment.shipping_method.id,
+ name: shipment.shipping_method.name,
+ code: shipment.shipping_method.code
}
end
- def serialize_stock_location
- return unless resource.stock_location
+ attribute :stock_location do |shipment|
+ next unless shipment.stock_location
{
- id: resource.stock_location.id,
- name: resource.stock_location.name
+ id: shipment.stock_location.id,
+ name: shipment.stock_location.name
}
end
- def serialize_shipping_rates
- resource.shipping_rates.map do |shipping_rate|
- shipping_rate_serializer.new(shipping_rate, nested_context('shipping_rates')).as_json
- end
- end
-
- # Serializer dependencies
- def shipping_rate_serializer
- Spree::Api::Dependencies.v3_storefront_shipping_rate_serializer.constantize
- end
+ many :shipping_rates,
+ resource: Spree.api.v3_storefront_shipping_rate_serializer,
+ if: proc { params[:includes]&.include?('shipping_rates') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/shipping_method_serializer.rb b/api/app/serializers/spree/api/v3/shipping_method_serializer.rb
index 3f05c7bd6a..6a025a775f 100644
--- a/api/app/serializers/spree/api/v3/shipping_method_serializer.rb
+++ b/api/app/serializers/spree/api/v3/shipping_method_serializer.rb
@@ -2,17 +2,8 @@ module Spree
module Api
module V3
class ShippingMethodSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- code: resource.code,
- tracking_url: resource.tracking_url,
- admin_name: resource.admin_name,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
- end
+ attributes :id, :name, :code, :tracking_url, :admin_name,
+ created_at: :iso8601, updated_at: :iso8601
end
end
end
diff --git a/api/app/serializers/spree/api/v3/shipping_rate_serializer.rb b/api/app/serializers/spree/api/v3/shipping_rate_serializer.rb
index ba5fd1904d..c1ea936d0e 100644
--- a/api/app/serializers/spree/api/v3/shipping_rate_serializer.rb
+++ b/api/app/serializers/spree/api/v3/shipping_rate_serializer.rb
@@ -2,18 +2,19 @@ module Spree
module Api
module V3
class ShippingRateSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- cost: resource.cost.to_f,
- display_cost: resource.display_cost.to_s,
- selected: resource.selected,
- shipping_method_id: resource.shipping_method_id,
- shipping_method_code: resource.shipping_method&.code,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :name, :selected, :shipping_method_id,
+ created_at: :iso8601, updated_at: :iso8601
+
+ attribute :cost do |shipping_rate|
+ shipping_rate.cost.to_f
+ end
+
+ attribute :display_cost do |shipping_rate|
+ shipping_rate.display_cost.to_s
+ end
+
+ attribute :shipping_method_code do |shipping_rate|
+ shipping_rate.shipping_method&.code
end
end
end
diff --git a/api/app/serializers/spree/api/v3/state_serializer.rb b/api/app/serializers/spree/api/v3/state_serializer.rb
index 0f0f6bfc7b..2a793b1e88 100644
--- a/api/app/serializers/spree/api/v3/state_serializer.rb
+++ b/api/app/serializers/spree/api/v3/state_serializer.rb
@@ -2,14 +2,7 @@ module Spree
module Api
module V3
class StateSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- abbr: resource.abbr,
- country_id: resource.country_id
- }
- end
+ attributes :id, :name, :abbr, :country_id
end
end
end
diff --git a/api/app/serializers/spree/api/v3/store_serializer.rb b/api/app/serializers/spree/api/v3/store_serializer.rb
index 19b54f8991..e3f26597b3 100644
--- a/api/app/serializers/spree/api/v3/store_serializer.rb
+++ b/api/app/serializers/spree/api/v3/store_serializer.rb
@@ -2,27 +2,17 @@ module Spree
module Api
module V3
class StoreSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- url: resource.url,
- meta_description: resource.meta_description,
- meta_keywords: resource.meta_keywords,
- seo_title: resource.seo_title,
- default_currency: resource.default_currency,
- code: resource.code,
- default: resource.default,
- supported_currencies: resource.supported_currencies_list.map(&:iso_code),
- facebook: resource.facebook,
- twitter: resource.twitter,
- instagram: resource.instagram,
- customer_support_email: resource.customer_support_email,
- default_locale: resource.default_locale,
- supported_locales: resource.supported_locales_list,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :name, :url, :meta_description, :meta_keywords, :seo_title,
+ :default_currency, :code, :default, :facebook, :twitter,
+ :instagram, :customer_support_email, :default_locale,
+ created_at: :iso8601, updated_at: :iso8601
+
+ attribute :supported_currencies do |store|
+ store.supported_currencies_list.map(&:iso_code)
+ end
+
+ attribute :supported_locales do |store|
+ store.supported_locales_list
end
end
end
diff --git a/api/app/serializers/spree/api/v3/taxon_serializer.rb b/api/app/serializers/spree/api/v3/taxon_serializer.rb
index 90442613d6..e6a6d3a7aa 100644
--- a/api/app/serializers/spree/api/v3/taxon_serializer.rb
+++ b/api/app/serializers/spree/api/v3/taxon_serializer.rb
@@ -2,64 +2,51 @@ module Spree
module Api
module V3
class TaxonSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- name: resource.name,
- description: resource.description.to_plain_text,
- description_html: resource.description.to_s,
- image_url: image_url(resource.image),
- square_image_url: image_url(resource.square_image),
- has_products: resource.active_products_with_descendants.exists?,
- is_root: resource.root?,
- is_child: resource.child?,
- is_leaf: resource.leaf?,
- permalink: resource.permalink,
- position: resource.position,
- lft: resource.lft,
- rgt: resource.rgt,
- depth: resource.depth,
- meta_title: resource.meta_title,
- meta_description: resource.meta_description,
- meta_keywords: resource.meta_keywords,
- parent_id: resource.parent_id,
- taxonomy_id: resource.taxonomy_id,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :name, :permalink, :position, :lft, :rgt, :depth,
+ :meta_title, :meta_description, :meta_keywords,
+ :parent_id, :taxonomy_id,
+ created_at: :iso8601, updated_at: :iso8601
- # Conditionally include children
- base_attrs[:parent] = serialize_parent if include?('parent')
- base_attrs[:children] = serialize_children if include?('children')
- base_attrs[:taxonomy] = serialize_taxonomy if include?('taxonomy')
-
- base_attrs
+ attribute :description do |taxon|
+ taxon.description.to_plain_text
end
- private
+ attribute :description_html do |taxon|
+ taxon.description.to_s
+ end
- def serialize_parent
- taxon_serializer.new(resource.parent, nested_context('parent')).as_json
+ attribute :image_url do |taxon|
+ image_url_for(taxon.image)
end
- def serialize_children
- resource.children.map do |child|
- taxon_serializer.new(child, nested_context('children')).as_json
- end
+ attribute :square_image_url do |taxon|
+ image_url_for(taxon.square_image)
end
- def serialize_taxonomy
- taxonomy_serializer.new(resource.taxonomy, nested_context('taxonomy')).as_json
+ attribute :is_root do |taxon|
+ taxon.root?
end
- # Serializer dependencies
- def taxon_serializer
- Spree::Api::Dependencies.v3_storefront_taxon_serializer.constantize
+ attribute :is_child do |taxon|
+ taxon.child?
end
- def taxonomy_serializer
- Spree::Api::Dependencies.v3_storefront_taxonomy_serializer.constantize
+ attribute :is_leaf do |taxon|
+ taxon.leaf?
end
+
+ # Conditional associations
+ one :parent,
+ resource: Spree.api.v3_storefront_taxon_serializer,
+ if: proc { params[:includes]&.include?('parent') }
+
+ many :children,
+ resource: Spree.api.v3_storefront_taxon_serializer,
+ if: proc { params[:includes]&.include?('children') }
+
+ one :taxonomy,
+ resource: Spree.api.v3_storefront_taxonomy_serializer,
+ if: proc { params[:includes]&.include?('taxonomy') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/taxonomy_serializer.rb b/api/app/serializers/spree/api/v3/taxonomy_serializer.rb
index 8e99a386da..1f706e7a50 100644
--- a/api/app/serializers/spree/api/v3/taxonomy_serializer.rb
+++ b/api/app/serializers/spree/api/v3/taxonomy_serializer.rb
@@ -2,35 +2,16 @@ module Spree
module Api
module V3
class TaxonomySerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- name: resource.name,
- }
+ attributes :id, :name
- base_attrs[:root] = serialize_root if include?('root')
- base_attrs[:taxons] = serialize_taxons if include?('taxons')
+ # Conditional associations
+ one :root,
+ resource: Spree.api.v3_storefront_taxon_serializer,
+ if: proc { params[:includes]&.include?('root') }
- base_attrs
- end
-
- private
-
- def serialize_root
- root_serializer.new(resource.root, nested_context('root')).as_json
- end
-
- def root_serializer
- Spree::Api::Dependencies.v3_storefront_taxon_serializer.constantize
- end
-
- def serialize_taxons
- taxons_serializer.new(resource.taxons, nested_context('taxons')).as_json
- end
-
- def taxons_serializer
- Spree::Api::Dependencies.v3_storefront_taxon_serializer.constantize
- end
+ many :taxons,
+ resource: Spree.api.v3_storefront_taxon_serializer,
+ if: proc { params[:includes]&.include?('taxons') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/user_serializer.rb b/api/app/serializers/spree/api/v3/user_serializer.rb
index 96a8ee2e40..9155535ff0 100644
--- a/api/app/serializers/spree/api/v3/user_serializer.rb
+++ b/api/app/serializers/spree/api/v3/user_serializer.rb
@@ -2,16 +2,8 @@ module Spree
module Api
module V3
class UserSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- email: resource.email,
- first_name: resource.first_name,
- last_name: resource.last_name,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
- end
+ attributes :id, :email, :first_name, :last_name,
+ created_at: :iso8601, updated_at: :iso8601
end
end
end
diff --git a/api/app/serializers/spree/api/v3/variant_serializer.rb b/api/app/serializers/spree/api/v3/variant_serializer.rb
index b68b2b2907..e4c1e01baf 100644
--- a/api/app/serializers/spree/api/v3/variant_serializer.rb
+++ b/api/app/serializers/spree/api/v3/variant_serializer.rb
@@ -2,87 +2,68 @@ module Spree
module Api
module V3
class VariantSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- name: resource.name,
- sku: resource.sku,
- barcode: resource.barcode,
- weight: resource.weight&.to_f,
- height: resource.height&.to_f,
- width: resource.width&.to_f,
- depth: resource.depth&.to_f,
- is_master: resource.is_master,
- options_text: resource.options_text,
- purchasable: resource.purchasable?,
- in_stock: resource.in_stock?,
- backorderable: resource.backorderable?,
- currency: currency,
- price: price_value,
- display_price: display_price_value,
- compare_at_price: compare_at_price_value,
- display_compare_at_price: display_compare_at_price_value
- }
-
- # Conditionally include associations
- base_attrs[:images] = serialize_images if include?('images')
- base_attrs[:option_values] = serialize_option_values if include?('option_values')
- base_attrs[:product] = serialize_product if include?('product')
-
- base_attrs
- end
+ attributes :id, :name, :sku, :barcode, :is_master, :options_text
- private
+ attribute :purchasable do |variant|
+ variant.purchasable?
+ end
- def price_value
- price = price_in_currency(resource)
- price&.amount&.to_f
+ attribute :in_stock do |variant|
+ variant.in_stock?
end
- def display_price_value
- price = price_in_currency(resource)
- price&.display_price&.to_s
+ attribute :backorderable do |variant|
+ variant.backorderable?
end
- def compare_at_price_value
- price = price_in_currency(resource)
- price&.compare_at_amount&.to_f
+ attribute :weight do |variant|
+ variant.weight&.to_f
end
- def display_compare_at_price_value
- price = price_in_currency(resource)
- return nil unless price&.compare_at_amount
+ attribute :height do |variant|
+ variant.height&.to_f
+ end
- Spree::Money.new(price.compare_at_amount, currency: currency).to_s
+ attribute :width do |variant|
+ variant.width&.to_f
end
- def serialize_images
- resource.images.map do |image|
- image_serializer.new(image, nested_context('images')).as_json
- end
+ attribute :depth do |variant|
+ variant.depth&.to_f
end
- def serialize_option_values
- resource.option_values.map do |option_value|
- option_value_serializer.new(option_value, nested_context('option_values')).as_json
- end
+ attribute :price do |variant|
+ price_object(variant)&.amount&.to_f
end
- def serialize_product
- product_serializer.new(resource.product, nested_context('product')).as_json if resource.product
+ attribute :display_price do |variant|
+ price_object(variant)&.display_price&.to_s
end
- # Serializer dependencies
- def image_serializer
- Spree::Api::Dependencies.v3_storefront_image_serializer.constantize
+ attribute :compare_at_price do |variant|
+ price_object(variant)&.compare_at_amount&.to_f
end
- def option_value_serializer
- Spree::Api::Dependencies.v3_storefront_option_value_serializer.constantize
+ attribute :display_compare_at_price do |variant|
+ price = price_object(variant)
+ next unless price&.compare_at_amount
+
+ Spree::Money.new(price.compare_at_amount, currency: currency).to_s
end
- def product_serializer
- Spree::Api::Dependencies.v3_storefront_product_serializer.constantize
+ # Conditional associations
+ many :images,
+ resource: Spree.api.v3_storefront_image_serializer,
+ if: proc { params[:includes]&.include?('images') }
+
+ many :option_values,
+ resource: Spree.api.v3_storefront_option_value_serializer,
+ if: proc { params[:includes]&.include?('option_values') }
+
+ private
+
+ def price_object(variant)
+ @price_object ||= price_for(variant)
end
end
end
diff --git a/api/app/serializers/spree/api/v3/wished_item_serializer.rb b/api/app/serializers/spree/api/v3/wished_item_serializer.rb
index 515428db76..4004f9dcdd 100644
--- a/api/app/serializers/spree/api/v3/wished_item_serializer.rb
+++ b/api/app/serializers/spree/api/v3/wished_item_serializer.rb
@@ -2,30 +2,11 @@ module Spree
module Api
module V3
class WishedItemSerializer < BaseSerializer
- def attributes
- base_attrs = {
- id: resource.id,
- quantity: resource.quantity,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :quantity, created_at: :iso8601, updated_at: :iso8601
- # Conditionally include variant
- base_attrs[:variant] = serialize_variant if include?('variant')
-
- base_attrs
- end
-
- private
-
- def serialize_variant
- variant_serializer.new(resource.variant, nested_context('variant')).as_json if resource.variant
- end
-
- # Serializer dependencies
- def variant_serializer
- Spree::Api::Dependencies.v3_storefront_variant_serializer.constantize
- end
+ one :variant,
+ resource: Spree.api.v3_storefront_variant_serializer,
+ if: proc { params[:includes]&.include?('variant') }
end
end
end
diff --git a/api/app/serializers/spree/api/v3/wishlist_serializer.rb b/api/app/serializers/spree/api/v3/wishlist_serializer.rb
index 137af8b145..dd81d77eba 100644
--- a/api/app/serializers/spree/api/v3/wishlist_serializer.rb
+++ b/api/app/serializers/spree/api/v3/wishlist_serializer.rb
@@ -2,34 +2,21 @@ module Spree
module Api
module V3
class WishlistSerializer < BaseSerializer
- def attributes
- {
- id: resource.id,
- name: resource.name,
- is_default: resource.is_default?,
- is_private: resource.is_private?,
- token: resource.token,
- created_at: timestamp(resource.created_at),
- updated_at: timestamp(resource.updated_at)
- }
+ attributes :id, :name, :token, created_at: :iso8601, updated_at: :iso8601
- # Conditionally include items
- base_attrs[:items] = serialize_items if include?('items')
-
- base_attrs
+ attribute :is_default do |wishlist|
+ wishlist.is_default?
end
- private
-
- def serialize_items
- resource.wished_items.map do |item|
- wished_item_serializer.new(item, nested_context('items')).as_json
- end
+ attribute :is_private do |wishlist|
+ wishlist.is_private?
end
- # Serializer dependencies
- def wished_item_serializer
- Spree::Api::Dependencies.v3_storefront_wished_item_serializer.constantize
+ many :items,
+ key: :items,
+ resource: Spree.api.v3_storefront_wished_item_serializer,
+ if: proc { params[:includes]&.include?('items') } do |wishlist|
+ wishlist.wished_items
end
end
end
diff --git a/api/config/initializers/alba.rb b/api/config/initializers/alba.rb
new file mode 100644
index 0000000000..4d5419e187
--- /dev/null
+++ b/api/config/initializers/alba.rb
@@ -0,0 +1,5 @@
+Alba.backend = :oj
+Alba.inflector = :active_support
+
+# Custom types
+Alba.register_type :iso8601, converter: ->(time) { time&.iso8601(3) }, auto_convert: true
diff --git a/api/config/initializers/ar_lazy_preload.rb b/api/config/initializers/ar_lazy_preload.rb
new file mode 100644
index 0000000000..f271667b4f
--- /dev/null
+++ b/api/config/initializers/ar_lazy_preload.rb
@@ -0,0 +1 @@
+ArLazyPreload.config.auto_preload = true
diff --git a/api/lib/spree/api.rb b/api/lib/spree/api.rb
index c60f5d6b4a..d9b200ef8b 100644
--- a/api/lib/spree/api.rb
+++ b/api/lib/spree/api.rb
@@ -2,6 +2,8 @@ require 'spree/core'
require 'jsonapi/serializer'
require 'doorkeeper'
require 'pagy'
+require 'alba'
+require 'oj'
module Spree
module Api
diff --git a/api/spec/controllers/spree/api/v3/http_caching_spec.rb b/api/spec/controllers/spree/api/v3/http_caching_spec.rb
new file mode 100644
index 0000000000..ceafe4aa7b
--- /dev/null
+++ b/api/spec/controllers/spree/api/v3/http_caching_spec.rb
@@ -0,0 +1,287 @@
+require 'spec_helper'
+
+class HttpCachingTestController < ActionController::API
+ include Spree::Api::V3::HttpCaching
+
+ attr_accessor :current_user
+
+ def current_currency
+ 'USD'
+ end
+
+ def current_locale
+ 'en'
+ end
+end
+
+describe Spree::Api::V3::HttpCaching, type: :controller do
+ let(:controller) { HttpCachingTestController.new }
+ let(:request) { instance_double(ActionDispatch::Request) }
+ let(:response) { ActionDispatch::Response.new }
+
+ before do
+ allow(controller).to receive(:request).and_return(request)
+ allow(controller).to receive(:response).and_return(response)
+ allow(controller).to receive(:params).and_return(ActionController::Parameters.new(params))
+ end
+
+ let(:params) { {} }
+
+ describe '#guest_user?' do
+ context 'when current_user is nil' do
+ before { controller.current_user = nil }
+
+ it 'returns true' do
+ expect(controller.send(:guest_user?)).to be true
+ end
+ end
+
+ context 'when current_user is present' do
+ let(:user) { create(:user) }
+
+ before { controller.current_user = user }
+
+ it 'returns false' do
+ expect(controller.send(:guest_user?)).to be false
+ end
+ end
+
+ context 'when current_user responds to guest? and returns true' do
+ let(:user) { double('User', guest?: true) }
+
+ before { controller.current_user = user }
+
+ it 'returns true' do
+ expect(controller.send(:guest_user?)).to be true
+ end
+ end
+ end
+
+ describe '#set_vary_headers' do
+ context 'for guest users' do
+ before { controller.current_user = nil }
+
+ it 'sets Vary header with Accept, X-Spree-Currency, X-Spree-Locale' do
+ controller.send(:set_vary_headers)
+ expect(response.headers['Vary']).to eq('Accept, X-Spree-Currency, X-Spree-Locale')
+ end
+
+ it 'does not set Cache-Control to private' do
+ controller.send(:set_vary_headers)
+ expect(response.headers['Cache-Control']).not_to include('private')
+ end
+ end
+
+ context 'for authenticated users' do
+ let(:user) { create(:user) }
+
+ before { controller.current_user = user }
+
+ it 'sets Cache-Control to private, no-store' do
+ controller.send(:set_vary_headers)
+ expect(response.headers['Cache-Control']).to eq('private, no-store')
+ end
+ end
+ end
+
+ describe '#cache_collection' do
+ let(:store) { @default_store }
+ let!(:products) { create_list(:product, 3, stores: [store]) }
+ let(:collection) { Spree::Product.where(id: products.map(&:id)) }
+
+ context 'for guest users' do
+ before do
+ controller.current_user = nil
+ allow(request).to receive(:fresh?).and_return(false)
+ end
+
+ it 'returns true to render response' do
+ result = controller.send(:cache_collection, collection)
+ expect(result).to be true
+ end
+
+ it 'sets ETag header' do
+ controller.send(:cache_collection, collection)
+ expect(response.headers['ETag']).to be_present
+ expect(response.headers['ETag']).to match(/^"[a-f0-9]{32}"$/)
+ end
+
+ it 'sets Cache-Control with public, max-age and stale-while-revalidate' do
+ controller.send(:cache_collection, collection)
+ cache_control = response.headers['Cache-Control']
+ expect(cache_control).to include('public')
+ expect(cache_control).to include('max-age=300')
+ expect(cache_control).to include('stale-while-revalidate=30')
+ end
+
+ context 'when client has fresh cache' do
+ before do
+ allow(request).to receive(:fresh?).and_return(true)
+ end
+
+ it 'returns false (304 Not Modified)' do
+ result = controller.send(:cache_collection, collection)
+ expect(result).to be false
+ end
+ end
+
+ context 'with custom expires_in' do
+ it 'sets custom max-age' do
+ controller.send(:cache_collection, collection, expires_in: 10.minutes)
+ cache_control = response.headers['Cache-Control']
+ expect(cache_control).to include('max-age=600')
+ end
+ end
+
+ context 'with custom stale_while_revalidate' do
+ it 'sets custom stale-while-revalidate' do
+ controller.send(:cache_collection, collection, stale_while_revalidate: 1.minute)
+ cache_control = response.headers['Cache-Control']
+ expect(cache_control).to include('stale-while-revalidate=60')
+ end
+ end
+ end
+
+ context 'for authenticated users' do
+ let(:user) { create(:user) }
+
+ before { controller.current_user = user }
+
+ it 'returns true without setting cache headers' do
+ result = controller.send(:cache_collection, collection)
+ expect(result).to be true
+ end
+
+ it 'does not set ETag header' do
+ controller.send(:cache_collection, collection)
+ expect(response.headers['ETag']).to be_nil
+ end
+
+ it 'does not set public Cache-Control' do
+ controller.send(:cache_collection, collection)
+ expect(response.headers['Cache-Control']).not_to include('public')
+ end
+ end
+ end
+
+ describe '#cache_resource' do
+ let(:store) { @default_store }
+ let!(:product) { create(:product, stores: [store]) }
+
+ context 'for guest users' do
+ before do
+ controller.current_user = nil
+ allow(controller).to receive(:stale?).and_return(true)
+ end
+
+ it 'returns true when resource is stale' do
+ result = controller.send(:cache_resource, product)
+ expect(result).to be true
+ end
+
+ it 'calls stale? with public: true' do
+ expect(controller).to receive(:stale?).with(product, public: true).and_return(true)
+ controller.send(:cache_resource, product)
+ end
+
+ it 'sets Cache-Control with public and max-age' do
+ controller.send(:cache_resource, product)
+ cache_control = response.headers['Cache-Control']
+ expect(cache_control).to include('public')
+ expect(cache_control).to include('max-age=300')
+ end
+
+ context 'when resource is fresh (304 Not Modified)' do
+ before do
+ allow(controller).to receive(:stale?).and_return(false)
+ end
+
+ it 'returns false' do
+ result = controller.send(:cache_resource, product)
+ expect(result).to be false
+ end
+ end
+
+ context 'with custom expires_in' do
+ it 'sets custom max-age' do
+ controller.send(:cache_resource, product, expires_in: 15.minutes)
+ cache_control = response.headers['Cache-Control']
+ expect(cache_control).to include('max-age=900')
+ end
+ end
+ end
+
+ context 'for authenticated users' do
+ let(:user) { create(:user) }
+
+ before { controller.current_user = user }
+
+ it 'returns true without calling stale?' do
+ expect(controller).not_to receive(:stale?)
+ result = controller.send(:cache_resource, product)
+ expect(result).to be true
+ end
+ end
+ end
+
+ describe '#collection_cache_key' do
+ let(:store) { @default_store }
+ let!(:products) { create_list(:product, 3, stores: [store]) }
+ let(:collection) { Spree::Product.where(id: products.map(&:id)) }
+
+ it 'includes collection cache_key_with_version' do
+ cache_key = controller.send(:collection_cache_key, collection)
+ expect(cache_key).to include(collection.cache_key_with_version)
+ end
+
+ context 'with include param' do
+ let(:params) { { include: 'variants,images' } }
+
+ it 'includes the include param in cache key' do
+ cache_key = controller.send(:collection_cache_key, collection)
+ expect(cache_key).to include('variants,images')
+ end
+ end
+
+ context 'with q (ransack) param' do
+ let(:params) { { q: { name_cont: 'test' } } }
+
+ it 'includes the q param in cache key' do
+ cache_key = controller.send(:collection_cache_key, collection)
+ expect(cache_key).to include('name_cont')
+ end
+ end
+
+ context 'with pagination params' do
+ let(:params) { { page: 2, per_page: 10 } }
+
+ it 'includes pagination params in cache key' do
+ cache_key = controller.send(:collection_cache_key, collection)
+ expect(cache_key).to include('2')
+ expect(cache_key).to include('10')
+ end
+ end
+
+ it 'includes current_currency in cache key' do
+ cache_key = controller.send(:collection_cache_key, collection)
+ expect(cache_key).to include('USD')
+ end
+
+ it 'includes current_locale in cache key' do
+ cache_key = controller.send(:collection_cache_key, collection)
+ expect(cache_key).to include('en')
+ end
+
+ context 'with different currencies' do
+ before do
+ allow(controller).to receive(:current_currency).and_return('EUR')
+ end
+
+ it 'generates different cache keys for different currencies' do
+ cache_key_eur = controller.send(:collection_cache_key, collection)
+ expect(cache_key_eur).to include('EUR')
+ expect(cache_key_eur).not_to include('USD')
+ end
+ end
+ end
+end
diff --git a/api/spree_api.gemspec b/api/spree_api.gemspec
index 9d6693e3de..1b19e5e688 100644
--- a/api/spree_api.gemspec
+++ b/api/spree_api.gemspec
@@ -26,9 +26,12 @@ Gem::Specification.new do |s|
s.add_development_dependency 'multi_json'
s.add_development_dependency 'rswag-specs'
+ s.add_dependency 'alba', '~> 3.0'
+ s.add_dependency 'ar_lazy_preload', '~> 2.0'
s.add_dependency 'bcrypt', '~> 3.1'
s.add_dependency 'doorkeeper', '~> 5.3'
s.add_dependency 'jsonapi-serializer', '~> 2.1'
+ s.add_dependency 'oj', '~> 3.16'
s.add_dependency 'pagy', '~> 43.0'
s.add_dependency 'spree_core', s.version
end