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.

Added Storefront API Posts and Post Categories endpoints (#13052)

Damian Legawiecc9563981c019
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 80865b9403..a1b6bef4a6 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -1,4 +1,5 @@
{
+ "$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": [
"Bash(rm:*)",
@@ -6,9 +7,9 @@
"Bash(bundle exec rspec:*)",
"Bash(bundle exec rails c:*)",
"Bash(ruby test:*)",
- "Bash(mv:*)"
+ "Bash(mv:*)",
+ "Bash(bundle exec rails:*)"
],
"deny": []
- },
- "$schema": "https://json.schemastore.org/claude-code-settings.json"
+ }
}
\ No newline at end of file
diff --git a/api/app/controllers/spree/api/v2/storefront/post_categories_controller.rb b/api/app/controllers/spree/api/v2/storefront/post_categories_controller.rb
new file mode 100644
index 0000000000..7504b216ae
--- /dev/null
+++ b/api/app/controllers/spree/api/v2/storefront/post_categories_controller.rb
@@ -0,0 +1,35 @@
+module Spree
+ module Api
+ module V2
+ module Storefront
+ class PostCategoriesController < ::Spree::Api::V2::ResourceController
+ protected
+
+ def collection
+ @collection ||= scope
+ end
+
+ def resource
+ @resource ||= find_with_fallback_default_locale { scope.friendly.find(params[:id]) } || scope.friendly.find(params[:id])
+ end
+
+ def collection_serializer
+ Spree::V2::Storefront::PostCategorySerializer
+ end
+
+ def resource_serializer
+ Spree::V2::Storefront::PostCategorySerializer
+ end
+
+ def model_class
+ Spree::PostCategory
+ end
+
+ def serializer_params
+ super.merge(include_posts: action_name == 'show')
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/api/app/controllers/spree/api/v2/storefront/posts_controller.rb b/api/app/controllers/spree/api/v2/storefront/posts_controller.rb
new file mode 100644
index 0000000000..fe569c17f9
--- /dev/null
+++ b/api/app/controllers/spree/api/v2/storefront/posts_controller.rb
@@ -0,0 +1,43 @@
+module Spree
+ module Api
+ module V2
+ module Storefront
+ class PostsController < ::Spree::Api::V2::ResourceController
+ protected
+
+ def collection
+ @collection ||= collection_finder.new(scope: scope, params: finder_params).execute
+ end
+
+ def resource
+ @resource ||= find_with_fallback_default_locale { scope.friendly.find(params[:id]) } || scope.friendly.find(params[:id])
+ end
+
+ def collection_finder
+ Spree::Api::Dependencies.storefront_posts_finder.constantize
+ end
+
+ def collection_serializer
+ Spree::V2::Storefront::PostSerializer
+ end
+
+ def resource_serializer
+ Spree::V2::Storefront::PostSerializer
+ end
+
+ def model_class
+ Spree::Post
+ end
+
+ def scope
+ super.published.includes(:post_category, image_attachment: :blob)
+ end
+
+ def allowed_sort_attributes
+ super << :published_at
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/api/app/serializers/spree/v2/storefront/post_category_serializer.rb b/api/app/serializers/spree/v2/storefront/post_category_serializer.rb
new file mode 100644
index 0000000000..a178d70bf1
--- /dev/null
+++ b/api/app/serializers/spree/v2/storefront/post_category_serializer.rb
@@ -0,0 +1,21 @@
+module Spree
+ module V2
+ module Storefront
+ class PostCategorySerializer < ::Spree::Api::V2::BaseSerializer
+ set_type :post_category
+
+ attributes :title, :slug, :created_at, :updated_at
+
+ attribute :description do |category|
+ category.description.to_plain_text if category.description.present?
+ end
+
+ has_many :posts, serializer: :post, record_type: :post, if: proc { |_record, params|
+ params[:include_posts] == true
+ } do |category|
+ category.posts.published.by_newest
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/api/app/serializers/spree/v2/storefront/post_serializer.rb b/api/app/serializers/spree/v2/storefront/post_serializer.rb
new file mode 100644
index 0000000000..d3b6ee0825
--- /dev/null
+++ b/api/app/serializers/spree/v2/storefront/post_serializer.rb
@@ -0,0 +1,45 @@
+module Spree
+ module V2
+ module Storefront
+ class PostSerializer < ::Spree::Api::V2::BaseSerializer
+ set_type :post
+
+ attributes :title, :slug, :published_at, :meta_title, :meta_description, :created_at, :updated_at
+
+ attribute :excerpt do |post|
+ post.excerpt.to_plain_text if post.excerpt.present?
+ end
+
+ attribute :content do |post|
+ post.content.to_plain_text if post.content.present?
+ end
+
+ attribute :description do |post|
+ post.description
+ end
+
+ attribute :shortened_description do |post|
+ post.shortened_description
+ end
+
+ attribute :author_name do |post|
+ post.author_name
+ end
+
+ attribute :post_category_title do |post|
+ post.post_category_title
+ end
+
+ attribute :tags do |post|
+ post.tag_list
+ end
+
+ attribute :image_url do |post, params|
+ url_helpers.cdn_image_url(post.image.attachment) if post.image.present? && post.image.attached?
+ end
+
+ belongs_to :post_category, serializer: :post_category, record_type: :post_category
+ end
+ end
+ end
+end
diff --git a/api/config/routes.rb b/api/config/routes.rb
index 88b3f4132c..23fd4d9586 100644
--- a/api/config/routes.rb
+++ b/api/config/routes.rb
@@ -67,6 +67,9 @@ Spree::Core::Engine.add_routes do
end
end
+ resources :posts, only: %i[index show]
+ resources :post_categories, only: %i[index show]
+
get '/digitals/:token', to: 'digitals#download', as: 'digital'
end
diff --git a/api/lib/spree/api/dependencies.rb b/api/lib/spree/api/dependencies.rb
index f972550867..043eca8a63 100644
--- a/api/lib/spree/api/dependencies.rb
+++ b/api/lib/spree/api/dependencies.rb
@@ -88,6 +88,7 @@ module Spree
storefront_credit_card_finder: -> { Spree::Dependencies.credit_card_finder },
storefront_find_by_variant_finder: -> { Spree::Dependencies.line_item_by_variant_finder },
storefront_products_finder: -> { Spree::Dependencies.products_finder },
+ storefront_posts_finder: -> { Spree::Dependencies.posts_finder },
storefront_taxon_finder: -> { Spree::Dependencies.taxon_finder },
storefront_variant_finder: -> { Spree::Dependencies.variant_finder },
diff --git a/api/spec/requests/spree/api/v2/storefront/post_categories_spec.rb b/api/spec/requests/spree/api/v2/storefront/post_categories_spec.rb
new file mode 100644
index 0000000000..71b511261b
--- /dev/null
+++ b/api/spec/requests/spree/api/v2/storefront/post_categories_spec.rb
@@ -0,0 +1,84 @@
+require 'spec_helper'
+
+describe 'API V2 Storefront Post Categories Spec', type: :request do
+ let!(:store) { @default_store }
+ let!(:admin_user) { create(:admin_user) }
+ let!(:post_categories) { create_list(:post_category, 3, store: store) }
+ let!(:post_category_with_posts) { create(:post_category, store: store) }
+ let!(:published_posts) { create_list(:post, 2, :published, store: store, author: admin_user, post_category: post_category_with_posts) }
+
+ before do
+ allow_any_instance_of(Spree::Api::V2::Storefront::PostCategoriesController).to receive(:current_store).and_return(store)
+ end
+
+ describe 'post_categories#index' do
+ context 'with no params' do
+ before { get '/api/v2/storefront/post_categories' }
+
+ it 'returns all post categories' do
+ expect(response.status).to eq(200)
+ expect(json_response['data'].count).to be >= 4
+ expect(json_response['data'].first).to have_type('post_category')
+ end
+
+ it 'returns post categories with correct attributes' do
+ category_data = json_response['data'].first['attributes']
+ expect(category_data).to include('title', 'slug', 'created_at', 'updated_at', 'description')
+ end
+
+ it 'does not include posts by default' do
+ expect(json_response['data'].first).not_to have_relationships(:posts)
+ end
+ end
+
+ end
+
+ describe 'post_categories#show' do
+ let(:category) { post_categories.first }
+
+ context 'with valid id' do
+ before { get "/api/v2/storefront/post_categories/#{category.id}" }
+
+ it 'returns the post category' do
+ expect(response.status).to eq(200)
+ expect(json_response['data']).to have_type('post_category')
+ expect(json_response['data']['attributes']['title']).to eq(category.title)
+ end
+
+ it 'includes posts relationship' do
+ expect(json_response['data']).to have_relationships(:posts)
+ end
+ end
+
+ context 'with friendly id (slug)' do
+ before { get "/api/v2/storefront/post_categories/#{category.slug}" }
+
+ it 'returns the category by slug' do
+ expect(response.status).to eq(200)
+ expect(json_response['data']['attributes']['title']).to eq(category.title)
+ end
+ end
+
+ context 'with category that has posts' do
+ before { get "/api/v2/storefront/post_categories/#{post_category_with_posts.id}" }
+
+ it 'returns the category with published posts only' do
+ expect(response.status).to eq(200)
+ expect(json_response['data']).to have_relationships(:posts)
+
+ if json_response['included']
+ posts_data = json_response['included'].select { |item| item['type'] == 'post' }
+ expect(posts_data.count).to eq(2)
+ end
+ end
+ end
+
+ context 'with invalid id' do
+ before { get '/api/v2/storefront/post_categories/invalid-id' }
+
+ it 'returns 404' do
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/api/spec/requests/spree/api/v2/storefront/posts_spec.rb b/api/spec/requests/spree/api/v2/storefront/posts_spec.rb
new file mode 100644
index 0000000000..4d515cbf75
--- /dev/null
+++ b/api/spec/requests/spree/api/v2/storefront/posts_spec.rb
@@ -0,0 +1,143 @@
+require 'spec_helper'
+
+describe 'API V2 Storefront Posts Spec', type: :request do
+ let(:store) { @default_store }
+ let!(:admin_user) { create(:admin_user) }
+ let!(:post_category) { create(:post_category, store: store) }
+ let!(:published_posts) { create_list(:post, 3, :published, store: store, author: admin_user, post_category: post_category) }
+ let!(:unpublished_post) { create(:post, store: store, author: admin_user, published_at: nil) }
+
+ before do
+ allow_any_instance_of(Spree::Api::V2::Storefront::PostsController).to receive(:current_store).and_return(store)
+ end
+
+ describe 'posts#index' do
+ context 'with no params' do
+ before do
+ allow_any_instance_of(Spree::Api::V2::Storefront::PostsController).to receive(:current_store).and_return(store)
+ get '/api/v2/storefront/posts'
+ end
+
+ it 'returns only published posts' do
+ expect(response.status).to eq(200)
+ expect(json_response['data'].count).to eq(3)
+ expect(json_response['data'].first).to have_type('post')
+ end
+
+ it 'returns posts with correct attributes' do
+ post_data = json_response['data'].first['attributes']
+ expect(post_data).to include(
+ 'title', 'slug', 'published_at', 'meta_title', 'meta_description',
+ 'created_at', 'updated_at', 'excerpt', 'content', 'description',
+ 'shortened_description', 'author_name', 'post_category_title', 'tags'
+ )
+ end
+
+ it 'includes post category relationship' do
+ expect(json_response['data'].first).to have_relationships(:post_category)
+ end
+ end
+
+ context 'with filtering by category' do
+ let!(:another_category) { create(:post_category, store: store) }
+ let!(:posts_in_another_category) { create_list(:post, 2, :published, store: store, author: admin_user, post_category: another_category) }
+
+ before { get "/api/v2/storefront/posts?filter[category_ids]=#{post_category.id}" }
+
+ it 'returns only posts from specified category' do
+ expect(response.status).to eq(200)
+ expect(json_response['data'].count).to eq(3)
+ json_response['data'].each do |post_data|
+ expect(post_data['relationships']['post_category']['data']['id']).to eq(post_category.id.to_s)
+ end
+ end
+ end
+
+ context 'with search query' do
+ let!(:searchable_post) { create(:post, :published, title: 'Special Search Title', store: store, author: admin_user) }
+
+ before { get '/api/v2/storefront/posts?q=Special' }
+
+ it 'returns posts matching search query' do
+ expect(response.status).to eq(200)
+ expect(json_response['data'].count).to eq(1)
+ expect(json_response['data'].first['attributes']['title']).to eq('Special Search Title')
+ end
+ end
+
+ context 'with sorting' do
+ before do
+ published_posts.first.update(published_at: 1.day.ago)
+ published_posts.last.update(published_at: 1.hour.ago)
+ end
+
+ before { get '/api/v2/storefront/posts?sort_by=published-newest' }
+
+ it 'returns posts sorted by published date' do
+ expect(response.status).to eq(200)
+ expect(json_response['data'].count).to eq(3)
+
+ published_dates = json_response['data'].map { |post| post['attributes']['published_at'] }
+ expect(published_dates).to eq(published_dates.sort.reverse)
+ end
+ end
+
+ context 'with tags filtering' do
+ let!(:tagged_post) { create(:post, :published, tag_list: ['ruby', 'rails'], store: store, author: admin_user) }
+
+ before { get '/api/v2/storefront/posts?filter[tags]=ruby,rails' }
+
+ it 'returns posts with specified tags' do
+ expect(response.status).to eq(200)
+ expect(json_response['data'].any? { |post| post['attributes']['tags'].include?('ruby') }).to be true
+ end
+ end
+ end
+
+ describe 'posts#show' do
+ let(:post) { published_posts.first }
+
+ context 'with valid id' do
+ before { get "/api/v2/storefront/posts/#{post.id}" }
+
+ it 'returns the post' do
+ expect(response.status).to eq(200)
+ expect(json_response['data']).to have_type('post')
+ expect(json_response['data']['attributes']['title']).to eq(post.title)
+ end
+
+ it 'includes all post attributes' do
+ post_attributes = json_response['data']['attributes']
+ expect(post_attributes).to include(
+ 'title', 'slug', 'published_at', 'excerpt', 'content',
+ 'author_name', 'post_category_title', 'tags'
+ )
+ end
+ end
+
+ context 'with friendly id (slug)' do
+ before { get "/api/v2/storefront/posts/#{post.slug}" }
+
+ it 'returns the post by slug' do
+ expect(response.status).to eq(200)
+ expect(json_response['data']['attributes']['title']).to eq(post.title)
+ end
+ end
+
+ context 'with unpublished post id' do
+ before { get "/api/v2/storefront/posts/#{unpublished_post.id}" }
+
+ it 'returns 404 for unpublished posts' do
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context 'with invalid id' do
+ before { get '/api/v2/storefront/posts/invalid-id' }
+
+ it 'returns 404' do
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/core/app/finders/spree/posts/find.rb b/core/app/finders/spree/posts/find.rb
new file mode 100644
index 0000000000..daff73aa39
--- /dev/null
+++ b/core/app/finders/spree/posts/find.rb
@@ -0,0 +1,137 @@
+module Spree
+ module Posts
+ class Find < Spree::BaseFinder
+ def initialize(scope:, params:)
+ super(scope: scope, params: params)
+ @scope = scope
+ @query = params[:q].presence&.strip
+ @ids = String(params.dig(:filter, :ids)).split(',')
+ @slugs = String(params.dig(:filter, :slugs)).split(',')
+ @category_ids = String(params.dig(:filter, :category_ids)).split(',')
+ @author_ids = String(params.dig(:filter, :author_ids)).split(',')
+ @tags = params.dig(:filter, :tags).to_s.split(',').compact_blank
+ @sort_by = params[:sort_by]
+ @published = params.dig(:filter, :published)
+ end
+
+ def execute
+ posts = by_ids(scope)
+ posts = by_slugs(posts)
+ posts = by_query(posts)
+ posts = by_category_ids(posts)
+ posts = by_author_ids(posts)
+ posts = by_tags(posts)
+ posts = by_published(posts)
+ posts = ordered(posts)
+
+ posts.distinct
+ end
+
+ private
+
+ attr_reader :scope, :query, :ids, :slugs, :category_ids, :author_ids, :tags, :sort_by, :published
+
+ def query?
+ query.present?
+ end
+
+ def ids?
+ ids.present?
+ end
+
+ def slugs?
+ slugs.present?
+ end
+
+ def category_ids?
+ category_ids.present?
+ end
+
+ def author_ids?
+ author_ids.present?
+ end
+
+ def tags?
+ tags.present?
+ end
+
+ def published?
+ published.present?
+ end
+
+ def sort_by?
+ sort_by.present?
+ end
+
+ def by_query(posts)
+ return posts unless query?
+
+ posts.search_by_title(query)
+ end
+
+ def by_ids(posts)
+ return posts unless ids?
+
+ posts.where(id: ids)
+ end
+
+ def by_slugs(posts)
+ return posts unless slugs?
+
+ posts.where(slug: slugs)
+ end
+
+ def by_category_ids(posts)
+ return posts unless category_ids?
+
+ posts.where(post_category_id: category_ids)
+ end
+
+ def by_author_ids(posts)
+ return posts unless author_ids?
+
+ posts.where(author_id: author_ids)
+ end
+
+ def by_tags(posts)
+ return posts if tags.empty?
+
+ posts.tagged_with(tags, any: true)
+ end
+
+ def by_published(posts)
+ return posts unless published?
+
+ case published.to_s
+ when 'true'
+ posts.published
+ when 'false'
+ posts.where(published_at: nil)
+ else
+ posts
+ end
+ end
+
+ def ordered(posts)
+ return posts unless sort_by?
+
+ case sort_by
+ when 'newest-first'
+ posts.by_newest
+ when 'oldest-first'
+ posts.order(created_at: :asc)
+ when 'published-newest'
+ posts.order(published_at: :desc)
+ when 'published-oldest'
+ posts.order(published_at: :asc)
+ when 'title-a-z'
+ posts.order(title: :asc)
+ when 'title-z-a'
+ posts.order(title: :desc)
+ else
+ posts
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/core/app/models/spree/ability.rb b/core/app/models/spree/ability.rb
index f8bb58d812..9d198ad1b2 100644
--- a/core/app/models/spree/ability.rb
+++ b/core/app/models/spree/ability.rb
@@ -101,6 +101,8 @@ module Spree
can :accept, Spree::Invitation, invitee_id: [user.id, nil], invitee_type: user.class.name, status: 'pending'
can :read, ::Spree::Policy
can :read, ::Spree::Page
+ can :read, ::Spree::Post
+ can :read, ::Spree::PostCategory
end
def protect_admin_role
diff --git a/core/lib/spree/core/dependencies.rb b/core/lib/spree/core/dependencies.rb
index 31a40718ca..a5e30d780b 100644
--- a/core/lib/spree/core/dependencies.rb
+++ b/core/lib/spree/core/dependencies.rb
@@ -103,6 +103,7 @@ module Spree
completed_order_finder: 'Spree::Orders::FindComplete',
credit_card_finder: 'Spree::CreditCards::Find',
products_finder: 'Spree::Products::Find',
+ posts_finder: 'Spree::Posts::Find',
taxon_finder: 'Spree::Taxons::Find',
line_item_by_variant_finder: 'Spree::LineItems::FindByVariant',
variant_finder: 'Spree::Variants::Find'
diff --git a/core/lib/spree/testing_support/factories/post_factory.rb b/core/lib/spree/testing_support/factories/post_factory.rb
index 2223e0c8aa..2f85da8a0f 100644
--- a/core/lib/spree/testing_support/factories/post_factory.rb
+++ b/core/lib/spree/testing_support/factories/post_factory.rb
@@ -10,5 +10,13 @@ FactoryBot.define do
trait :with_image do
image { Rack::Test::UploadedFile.new(Spree::Core::Engine.root.join('spec/fixtures/thinking-cat.jpg'), 'image/jpeg') }
end
+
+ trait :published do
+ published_at { Time.current }
+ end
+
+ trait :unpublished do
+ published_at { nil }
+ end
end
end