summaryrefslogtreecommitdiff
path: root/lib/chef_zero/rest_base.rb
diff options
context:
space:
mode:
authorjkeiser <jkeiser@opscode.com>2012-12-19 23:22:54 -0800
committerjkeiser <jkeiser@opscode.com>2012-12-19 23:23:21 -0800
commit666374b272a8851a2c57530a71a6183d4d06a648 (patch)
treeb53efd8134aa36ab0d459f3e4e87e1a6bbd1fe21 /lib/chef_zero/rest_base.rb
downloadchef-zero-666374b272a8851a2c57530a71a6183d4d06a648.tar.gz
Initial commit (moved/split up from jk/tiny-chef-server branch of jkeiser/chef)
Diffstat (limited to 'lib/chef_zero/rest_base.rb')
-rw-r--r--lib/chef_zero/rest_base.rb82
1 files changed, 82 insertions, 0 deletions
diff --git a/lib/chef_zero/rest_base.rb b/lib/chef_zero/rest_base.rb
new file mode 100644
index 0000000..068a55d
--- /dev/null
+++ b/lib/chef_zero/rest_base.rb
@@ -0,0 +1,82 @@
+require 'chef_zero/rest_request'
+require 'chef_zero/rest_error_response'
+
+module ChefZero
+ class RestBase
+ def initialize(server)
+ @server = server
+ end
+
+ attr_reader :server
+
+ def data
+ server.data
+ end
+
+ def call(env)
+ begin
+ rest_path = env['PATH_INFO'].split('/').select { |part| part != "" }
+ method = env['REQUEST_METHOD'].downcase.to_sym
+ if !self.respond_to?(method)
+ accept_methods = [:get, :put, :post, :delete].select { |m| self.respond_to?(m) }
+ accept_methods_str = accept_methods.map { |m| m.to_s.upcase }.join(', ')
+ return [405, {"Content-Type" => "text/plain", "Allow" => accept_methods_str}, "Bad request method for '#{env['REQUEST_PATH']}': #{env['REQUEST_METHOD']}"]
+ end
+ if json_only && !env['HTTP_ACCEPT'].split(';').include?('application/json')
+ return [406, {"Content-Type" => "text/plain"}, "Must accept application/json"]
+ end
+ # Dispatch to get()/post()/put()/delete()
+ begin
+ self.send(method, RestRequest.new(env))
+ rescue RestErrorResponse => e
+ error(e.response_code, e.error)
+ end
+ rescue
+ puts $!.inspect
+ puts $!.backtrace
+ raise
+ end
+ end
+
+ def json_only
+ true
+ end
+
+ def get_data(request, rest_path=nil)
+ rest_path ||= request.rest_path
+ # Grab the value we're looking for
+ value = data
+ rest_path.each do |path_part|
+ if !value.has_key?(path_part)
+ raise RestErrorResponse.new(404, "Object not found: #{build_uri(request.base_uri, rest_path)}")
+ end
+ value = value[path_part]
+ end
+ value
+ end
+
+ def error(response_code, error)
+ json_response(response_code, {"error" => [error]})
+ end
+
+ def json_response(response_code, json)
+ already_json_response(response_code, JSON.pretty_generate(json))
+ end
+
+ def already_json_response(response_code, json_text)
+ [response_code, {"Content-Type" => "application/json"}, json_text]
+ end
+
+ def build_uri(base_uri, rest_path)
+ RestBase::build_uri(base_uri, rest_path)
+ end
+
+ def self.build_uri(base_uri, rest_path)
+ "#{base_uri}/#{rest_path.join('/')}"
+ end
+
+ def populate_defaults(request, response)
+ response
+ end
+ end
+end