Fill out customers controller

Add customer serializer
This commit is contained in:
Matt-Yorkley
2021-10-11 11:26:48 +01:00
committed by Maikel Linke
parent 3128232d7e
commit cc4192047e
4 changed files with 87 additions and 4 deletions

View File

@@ -57,6 +57,7 @@ gem 'devise-token_authenticatable'
gem 'jwt', '~> 2.3'
gem 'oauth2', '~> 1.4.7' # Used for Stripe Connect
gem 'jsonapi-serializer'
gem 'pagy', '~> 5.1'
gem 'rswag-api'

View File

@@ -346,6 +346,8 @@ GEM
json_spec (1.1.5)
multi_json (~> 1.0)
rspec (>= 2.0, < 4.0)
jsonapi-serializer (2.2.0)
activesupport (>= 4.2)
jwt (2.3.0)
knapsack (4.0.0)
rake
@@ -739,6 +741,7 @@ DEPENDENCIES
jquery-ui-rails (~> 4.2)
json
json_spec (~> 1.1.4)
jsonapi-serializer
jwt (~> 2.3)
knapsack
letter_opener (>= 1.4.1)

View File

@@ -1,15 +1,81 @@
# frozen_string_literal: true
require 'open_food_network/permissions'
module Api
module V1
class CustomersController < Api::V1::BaseController
def index; end
skip_authorization_check only: :index
def show; end
before_action :set_customer, only: [:show, :update, :destroy]
before_action :authorize_action, only: [:show, :update, :destroy]
def update; end
def index
customers = search_customers
def destroy; end
render json: Api::V1::CustomerSerializer.new(customers, is_collection: true)
end
def show
render json: Api::V1::CustomerSerializer.new(@customer)
end
def create
authorize! :update, Enterprise.find(customer_params[:enterprise_id])
@customer = Customer.new(customer_params)
if @customer.save
render json: Api::V1::CustomerSerializer.new(@customer), status: :created
else
invalid_resource! @customer
end
end
def update
if @customer.update(customer_params)
render json: Api::V1::CustomerSerializer.new(@customer)
else
invalid_resource! @customer
end
end
def destroy
if @customer.destroy
render json: Api::V1::CustomerSerializer.new(@customer)
else
invalid_resource! @customer
end
end
private
def set_customer
@customer = Customer.find(params[:id])
end
def authorize_action
authorize! action_name.to_sym, @customer
end
def search_customers
customers = visible_customers
customers = customers.where(enterprise_id: params[:enterprise_id]) if params[:enterprise_id]
customers.ransack(params[:q]).result
end
def visible_customers
Customer.where(user_id: current_api_user.id).or(
Customer.where(enterprise_id: editable_enterprises)
)
end
def customer_params
params.require(:customer).permit(:email, :enterprise_id)
end
def editable_enterprises
OpenFoodNetwork::Permissions.new(current_api_user).editable_enterprises.select(:id)
end
end
end
end

View File

@@ -0,0 +1,13 @@
# frozen_string_literal: true
module Api
module V1
class CustomerSerializer
include JSONAPI::Serializer
attributes :id, :enterprise_id, :name, :code, :email
belongs_to :enterprise, record_type: :enterprise, serializer: :id
end
end
end