Skip to content

Commit

Permalink
feat: add monetary data validator
Browse files Browse the repository at this point in the history
  • Loading branch information
shaojunda committed May 25, 2020
1 parent 9eb2b13 commit ed14322
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
13 changes: 13 additions & 0 deletions app/controllers/api/v1/monetary_data_controller.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
module Api
module V1
class MonetaryDataController < ApplicationController
before_action :validate_query_params, only: :show

def show
monetary_data = MonetaryData.new

render json: MonetaryDataSerializer.new(monetary_data, params: { indicator: params[:id] })
end

def validate_query_params
validator = Validations::DistributionData.new(params)

if validator.invalid?
errors = validator.error_object[:errors]
status = validator.error_object[:status]

render json: errors, status: status
end
end
end
end
end
33 changes: 33 additions & 0 deletions app/controllers/validations/monetary_data.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module Validations
class MonetaryData
include ActiveModel::Validations

validate :query_key_format_must_be_correct

def initialize(params = {})
@query_key = params[:id]
end

def error_object
api_errors = []

if invalid?
api_errors << Api::V1::Exceptions::IndicatorNameInvalidError.new if :query_key.in?(errors.keys)
{
status: api_errors.first.status,
errors: RequestErrorSerializer.new(api_errors, message: api_errors.first.title)
}
end
end

private

attr_accessor :query_key

def query_key_format_must_be_correct
if query_key.blank? || !(query_key.split("-") - ::MonetaryData::VALID_INDICATORS).empty?
errors.add(:query_key, "indicator name is invalid")
end
end
end
end

0 comments on commit ed14322

Please sign in to comment.