api_recipes 2.10.4 → 3.0.0.beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,141 +1,91 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module ApiRecipes
4
+ # One step of a chain: a node of the tree with its path filled. The
5
+ # subclass generated for the node adds a method per child.
6
+ #
7
+ # Every method of this class is a name an endpoint cannot use as a method:
8
+ # the class has only the public methods below, and inside them the only
9
+ # private methods called are raise and block_given?.
2
10
  class Endpoint
3
-
4
- attr_reader :api, :name, :params, :route, :children
5
-
6
- FORWARDABLE_PARAMS = %i[verify_with].freeze
7
-
8
- def initialize(api: nil, name: nil, path: nil, params: {}, request_params: [], &block)
9
- @api = api
10
- @name = name
11
- @path = path.to_s
12
- new_params = params.dup || {}
13
- self.params = new_params
14
- @children = new_params.delete :endpoints
15
- @route = nil
16
- @request_params = request_params.extract_options!
17
- self.path_params = request_params
18
-
19
- generate_route
20
- generate_children
21
- if block_given?
22
- run &block
23
- end
24
- end
25
-
26
- def run(&block)
27
- if @route
28
- @route.start_request &block
11
+ # One Proc for all the endpoints: a block written in initialize costs an
12
+ # object per endpoint, in a chain that is built again at every call.
13
+ UPGRADE_WARNING = proc { |param, kind, endpoint| Internals::Registry.warn_upgrade(endpoint, param, kind) }
14
+
15
+ # args: the path values, then optionally a Hash of options for http.rb.
16
+ # overrides: the options given to with, for this request only.
17
+ def initialize(context, definition, parent_path, args, overrides = nil)
18
+ @context = context
19
+ @definition = definition
20
+ @parent_path = parent_path
21
+ @args = args
22
+ @overrides = overrides
23
+ last = args.last
24
+ @options = last.is_a?(Hash) ? last : nil
25
+ params = definition.path_params
26
+ count = @options ? args.size - 1 : args.size
27
+ raise PathParamsMismatch.new(definition.full_path, params, args.first(count)) unless count == params.size
28
+
29
+ own = definition.template.expand(args, endpoint: definition.full_name, &UPGRADE_WARNING)
30
+ if own.empty?
31
+ # A root endpoint with an empty path is the address of the api, which
32
+ # ends with a slash; a nested one is the address of its parent.
33
+ root = definition.parent.is_a?(Internals::Definition::Api) && !parent_path.end_with?('/')
34
+ @path = root ? "#{parent_path}/".freeze : parent_path
29
35
  else
30
- raise NoRouteExists.new @name
36
+ path = "#{parent_path}/#{own}"
37
+ path.squeeze!('/')
38
+ @path = path.freeze
31
39
  end
32
40
  end
33
41
 
34
- def url
35
- if @route
36
- @route.url
37
- else
38
- ApiRecipes.logger.debug "No route configured for '#{api.name}#{absolute_path}': Is option 'route: no' present?"
39
- nil
40
- end
42
+ # The child called name. With a block, sends its request at once.
43
+ def [](name, *args, &block)
44
+ endpoint = @context.handles.endpoint(@context, @definition, @path, name, args)
45
+ endpoint.run(&block) if block
46
+ endpoint
41
47
  end
42
48
 
43
- private
44
-
45
- def generate_route
46
- # Check if we have to generate route for this endpoint
47
- if create_route?
48
- ensure_route_does_not_clash @name
49
- # Generate route
50
- attrs = params.dup
51
- attrs.delete(:endpoints)
52
- # puts "Generating route '#{@name}' with path '#{build_path}'"
53
- @route = Route.new(api: @api, endpoint: self, path: build_path, attributes: attrs, req_pars: @request_params)
54
- end
49
+ # Sends the request. With a block, passes it the response.
50
+ def run
51
+ response = Internals::Request.new(context: @context, definition: @definition, path: @path, options: @options,
52
+ overrides: @overrides).perform
53
+ yield response if block_given?
54
+ response
55
55
  end
56
56
 
57
- def generate_children
58
- # Generate children endpoints if any
59
- # puts "generating children of #{@name}: #{children.inspect}"
60
- if children
61
- children.each do |ep_name, pars|
62
- pars = forwardable_params.merge(pars) if pars
63
- # TODO: Merge pars with params
64
- # puts "Creating Endpoint '#{@name}' child '#{ep_name}' passing path #{build_path}"
65
- define_singleton_method ep_name do |*request_params, &block|
66
- Endpoint.new api: @api, name: ep_name, path: build_path, params: pars, request_params: request_params, &block
67
- end
68
- end
69
- end
57
+ # The URL without the query string, or nil without a route. Sends nothing.
58
+ def url
59
+ Internals::Request.new(context: @context, definition: @definition, path: @path, options: @options,
60
+ overrides: @overrides).url
70
61
  end
71
62
 
72
- def ensure_route_does_not_clash(route_name)
73
- # Check if a method named route_name has already been defined on this object
74
- if respond_to? route_name
75
- raise RouteNameClashWithExistentMethod.new(@name, route_name)
63
+ # A copy with options for this request only, not for the children. An
64
+ # option given as nil drops the one given before.
65
+ def with(options)
66
+ overrides = Internals::Compiler.resolve_options(options, :with_endpoint)
67
+ if @overrides
68
+ merged = @overrides.merge(overrides)
69
+ options.each { |key, value| merged.delete(key.to_sym) if value.nil? }
70
+ overrides = merged.freeze
76
71
  end
72
+ self.class.new(@context, @definition, @parent_path, @args, overrides)
77
73
  end
78
74
 
79
- def create_route?
80
- res = params[:route].eql?('yes') || params[:route].eql?(true)
81
- res
82
- end
75
+ attr_reader :definition
83
76
 
84
- def absolute_path
85
- # Append path passed to initialize and (params[:path] || @name)
86
- append = params[:path] || @name
87
- unless append.empty?
88
- "#{@path}/#{append}"
89
- else
90
- "#{@path}"
91
- end.gsub(/\/+/, '/') # remove multiple consecutive '//'
92
- end
93
-
94
- def params=(attrs)
95
- unless attrs.is_a? Hash
96
- raise ArgumentError, "provided 'attrs' must be an Hash"
97
- end
98
- # Merge DEFAULT_ROUTE_ATTRIBUTES with Api base_configs
99
- # Then merge the result with provided attributes
100
- @params = Settings::DEFAULT_ROUTE_ATTRIBUTES.inject({}) do |out, key_val|
101
- new_val = @api.base_configs[key_val.first]
102
- out[key_val.first] = new_val.nil? ? key_val.last : new_val
103
- out
104
- end.inject({}) do |out, key_val|
105
- new_val = attrs[key_val.first]
106
- out[key_val.first] = new_val.nil? ? key_val.last : new_val
107
- out
108
- end
77
+ def inspect
78
+ "#<ApiRecipes::Endpoint #{@definition.full_name} #{@definition.verb.to_s.upcase} " \
79
+ "#{@context.shown_origin}#{@path}>"
109
80
  end
110
81
 
111
- def build_path
112
- final_path = absolute_path
113
- # Check if provided path_params match with required path params
114
- req_params = required_params_for_path
115
- if @path_params.size != req_params.size
116
- # puts "\nWARNING\n"
117
- raise PathParamsMismatch.new(final_path, req_params, @path_params)
118
- end
119
- # Replace required_params present in path with params provided by user (@path_params)
120
- @path_params.each { |par| final_path.sub! /(:[^\/]+)/, par.to_s }
82
+ # An Endpoint holds options that can contain secrets: it is never serialized.
83
+ def marshal_dump = raise(TypeError, 'an ApiRecipes::Endpoint cannot be serialized')
121
84
 
122
- final_path
123
- end
85
+ def encode_with(_coder) = raise(TypeError, 'an ApiRecipes::Endpoint cannot be serialized')
124
86
 
125
- def path_params=(params)
126
- unless params.is_a? Array
127
- raise ArgumentError, 'path params must be an Array'
128
- end
129
- # Merge route attributes with defaults and deep clone route attributes
130
- @path_params = params
131
- end
87
+ def as_json(*) = raise(TypeError, 'an ApiRecipes::Endpoint cannot be serialized')
132
88
 
133
- def required_params_for_path
134
- absolute_path.scan(/:(\w+)/).flatten.map { |p| p.to_sym }
135
- end
136
-
137
- def forwardable_params
138
- params.select { |k, v| FORWARDABLE_PARAMS.include? k }
139
- end
89
+ def to_json(*) = raise(TypeError, 'an ApiRecipes::Endpoint cannot be serialized')
140
90
  end
141
91
  end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ class Error < StandardError; end
5
+
6
+ class ConfigurationError < Error
7
+ attr_reader :errors
8
+
9
+ def initialize(errors)
10
+ @errors = errors
11
+ count = errors.size
12
+ noun = count == 1 ? 'problem' : 'problems'
13
+ super("#{count} #{noun} in the configuration\n #{errors.join("\n ")}")
14
+ end
15
+ end
16
+
17
+ class RecipeFileError < ConfigurationError
18
+ attr_reader :path
19
+
20
+ def initialize(path, reason)
21
+ @path = path
22
+ super(["#{path}: #{reason}"])
23
+ end
24
+ end
25
+
26
+ class InvalidPathParameter < Error
27
+ def initialize(endpoint, param, reason)
28
+ super("invalid value for path parameter '#{param}' of '#{endpoint}': #{reason}")
29
+ end
30
+ end
31
+
32
+ class UnknownEndpoint < Error
33
+ # A name that is not printable text in a known encoding is shown with inspect.
34
+ def initialize(parent, name, available)
35
+ shown = name.to_s if name.is_a?(String) || name.is_a?(Symbol)
36
+ unless shown && [Encoding::UTF_8, Encoding::US_ASCII].include?(shown.encoding) && shown.valid_encoding? &&
37
+ !shown.match?(/[[:cntrl:]]/)
38
+ shown = name.inspect
39
+ end
40
+ super("'#{parent}' has no endpoint '#{shown}'. Available: #{available.join(', ')}")
41
+ end
42
+ end
43
+
44
+ class MissingVariable < Error
45
+ def initialize(api, variable)
46
+ super("api '#{api}' requires the variable '#{variable}' but it was not provided")
47
+ end
48
+ end
49
+
50
+ class InvalidVariable < Error
51
+ def initialize(api, variable, reason)
52
+ super("invalid value for variable '#{variable}' of api '#{api}': #{reason}")
53
+ end
54
+ end
55
+
56
+ class InvalidCredential < Error
57
+ def initialize(reason)
58
+ super("invalid credential: #{reason}")
59
+ end
60
+ end
61
+
62
+ class InvalidUrl < Error
63
+ def initialize(reason)
64
+ super("invalid url: #{reason}")
65
+ end
66
+ end
67
+
68
+ class CredentialOriginMismatch < Error
69
+ def initialize(api, credential_origin, request_origin)
70
+ if credential_origin
71
+ super("api '#{api}': the credential is bound to #{credential_origin.inspect} but the request goes to " \
72
+ "#{request_origin.inspect}. Set the credential at the level that changes the destination, " \
73
+ 'or set it to nil to send none')
74
+ else
75
+ super("api '#{api}': the origin of the credential cannot be determined at the level that holds it " \
76
+ '(for example, a variable of the host has no value there), so it is not sent to ' \
77
+ "#{request_origin.inspect}. Set the credential at the level that sets the destination, " \
78
+ 'or give the level that holds it the values its host needs')
79
+ end
80
+ end
81
+ end
82
+
83
+ class ApiNameClashError < Error
84
+ # declared_in: the class or module of the hierarchy that already declares the api.
85
+ def initialize(owner, name, declared_in = nil)
86
+ if owner.is_a?(Module) && owner.singleton_class?
87
+ super("api '#{name}' cannot be declared on a singleton class: declare it in a module and extend the " \
88
+ 'object with it')
89
+ elsif declared_in
90
+ super("api '#{name}' is already declared by #{declared_in}: an api can be declared once per class " \
91
+ 'hierarchy. Use with(...) for other options')
92
+ else
93
+ super("#{owner} already has a method called '#{name}'. Give the api another method name with as:")
94
+ end
95
+ end
96
+ end
97
+
98
+ class PathParamsMismatch < Error
99
+ def initialize(path, expected_params, provided_params)
100
+ if expected_params.size == 0
101
+ message = "route '#{path}' requires NO PARAMS but #{provided_params} were provided"
102
+ else
103
+ message = "route '#{path}' requires params #{expected_params} but #{provided_params} were provided"
104
+ end
105
+ super(message)
106
+ end
107
+ end
108
+
109
+ class ResponseCodeNotAsExpected < Error
110
+
111
+ attr_reader :path, :expected_code, :response
112
+
113
+ def initialize(path, expected_code = nil, response = nil, message: nil)
114
+ @path = path
115
+ @expected_code = expected_code
116
+ @response = response
117
+ unless message
118
+ message = "response code for request on route '#{@path}' has returned '#{@response.code}', but '#{@expected_code}' was expected"
119
+ end
120
+ super(message)
121
+ end
122
+ end
123
+
124
+ class ApiConfigIsNotAnHash < Error
125
+ def initialize(endpoint)
126
+ message = "provided config for endpoint '#{endpoint}' must be an Hash"
127
+ super(message)
128
+ end
129
+ end
130
+
131
+ class NoRouteExists < Error
132
+ def initialize(endpoint_name)
133
+ message = "no route defined on #{endpoint_name}"
134
+ super(message)
135
+ end
136
+ end
137
+ end