Files
discourse-subscriptions/app/controllers/products_controller.rb
T

64 lines
1.3 KiB
Ruby
Raw Normal View History

2019-10-25 08:18:16 +11:00
# frozen_string_literal: true
2019-12-04 11:23:45 +11:00
module DiscourseSubscriptions
2019-10-25 08:18:16 +11:00
class ProductsController < ::ApplicationController
2019-12-04 11:23:45 +11:00
include DiscourseSubscriptions::Stripe
2019-10-25 08:18:16 +11:00
before_action :set_api_key
def index
begin
2020-05-22 11:20:05 -05:00
product_ids = Product.all.pluck(:external_id)
products = []
2019-10-25 08:18:16 +11:00
2020-05-22 11:20:05 -05:00
if product_ids.present?
response = ::Stripe::Product.list({
ids: product_ids,
active: true
})
products = response[:data].map do |p|
serialize(p)
end
2019-11-04 16:37:21 +11:00
end
render_json_dump products
2019-10-25 08:18:16 +11:00
rescue ::Stripe::InvalidRequestError => e
2019-12-12 09:59:38 +11:00
render_json_error e.message
2019-10-25 08:18:16 +11:00
end
end
2019-11-04 16:37:21 +11:00
def show
begin
product = ::Stripe::Product.retrieve(params[:id])
render_json_dump serialize(product)
rescue ::Stripe::InvalidRequestError => e
2019-12-12 09:59:38 +11:00
render_json_error e.message
2019-11-04 16:37:21 +11:00
end
end
private
def serialize(product)
{
id: product[:id],
name: product[:name],
description: product[:metadata][:description],
subscribed: current_user_products.include?(product[:id])
2019-11-04 16:37:21 +11:00
}
end
def current_user_products
2019-12-03 14:31:15 +11:00
return [] if current_user.nil?
2020-05-22 11:20:05 -05:00
Customer
.select(:product_id)
.where(user_id: current_user.id)
.map { |c| c.product_id }.compact
end
2019-10-25 08:18:16 +11:00
end
end