./lib/joshua/base_instance.rb in joshua-0.2.4 vs ./lib/joshua/base_instance.rb in joshua-0.2.7
- old
+ new
@@ -22,20 +22,24 @@
:response,
:uid
attr_reader :api
- def initialize action, params: {}, opts: {}, development: false, id: nil, bearer: nil, api_host: nil
+ def initialize action, params: {}, opts: {}, development: false, id: nil, bearer: nil, api_host: nil, html_safe: true
@api = INSTANCE.new
if action.is_a?(Array)
# unpack id and action is action is given in path form # [123, :show]
@api.id, @api.action = action[1] ? action : [nil, action[0]]
else
@api.action = action
end
+ if html_safe
+ params = Joshua.make_hash_html_safe params
+ end
+
@api.bearer = bearer
@api.id ||= id
@api.action = @api.action.to_sym
@api.request = api_host ? api_host.request : nil
@api.method_opts = self.class.opts.dig(@api.id ? :member : :collection, @api.action) || {}
@@ -45,13 +49,15 @@
@api.api_host = api_host
@api.response = ::Joshua::Response.new @api
end
def execute_call
- if !@api.development && @api.request && @api.request.request_method == 'GET' && !@api.method_opts[:gettable]
- response.error 'GET request is not allowed'
- else
+ allow_type = @api.method_opts[:allow] || 'POST'
+ request_type = @api.request&.request_method || 'POST'
+ is_allowed = @api.development || ['POST', allow_type].include?(request_type)
+
+ if is_allowed
begin
parse_api_params
parse_annotations unless response.error?
resolve_api_body unless response.error?
rescue Joshua::Error => error
@@ -70,10 +76,12 @@
end
end
# we execute generic after block in case of error or no
execute_callback :after_all
+ else
+ response.error '%s request is not allowed' % request_type
end
@api.raw || response.render
end
@@ -98,22 +106,25 @@
end
end
end
def resolve_api_body &block
+ # if we have model defiend, we execute member otherwise collection
+ type = @api.id ? :member : :collection
+ api_method = '_api_%s_%s' % [type, @api.action]
+
+ unless respond_to?(api_method)
+ raise Joshua::Error, "Api method #{type}:#{@api.action} not found"
+ end
+
# execute before "in the wild"
# model @api.pbject should be set here
execute_callback :before_all
instance_exec &block if block
- # if we have model defiend, we execute member otherwise collection
- type = @api.id ? :member : :collection
-
execute_callback 'before_%s' % type
- api_method = '_api_%s_%s' % [type, @api.action]
- raise Joshua::Error, "Api method #{type}:#{@api.action} not found" unless respond_to?(api_method)
data = send api_method
response.data data unless response.data?
# after blocks
@@ -154,19 +165,22 @@
@api.params
end
# inline error raise
def error text, args={}
- puts 'JOSHUA API Error: %s (%s)' % [text, caller[0]] if @api.development
+ if @api.development
+ puts 'JOSHUA API Error: %s (%s)' % [text, caller[0]]
+ end
if err = RESCUE_FROM[text]
if err.is_a?(Proc)
err.call
return
else
response.error err, args
end
else
+ rr text
response.error text, args
end
raise Joshua::Error, text
end