Major update, primarily to add pagination support.
* Added Reference objects to encapsulate API calls. * Added Result objects to encapsulate API responses. * Changed the return value of APIClient#execute to Result. * Changed the method signature of APIClient#execute to support named params. * Added APIClient#execute! which throws exceptions on error. * Added automatic parsing code to better allow for complex nested structures. * Added error parser. * Added module for pagination in parsers.
This commit is contained in:
1 parent
a656c13862
commit
f336ab34a7
15 files changed
+821
-306
No files matched your search
@@ -144,7 +144,7 @@ module Google
|
||||
def resources
|
||||
return @resources ||= (
|
||||
(@discovery_document['resources'] || []).inject([]) do |accu, (k, v)|
|
||||
accu << ::Google::APIClient::Resource.new(self.method_base, k, v)
|
||||
accu << Google::APIClient::Resource.new(self.method_base, k, v)
|
||||
accu
|
||||
end
|
||||
)
|
||||
@@ -158,7 +158,7 @@ module Google
|
||||
def methods
|
||||
return @methods ||= (
|
||||
(@discovery_document['methods'] || []).inject([]) do |accu, (k, v)|
|
||||
accu << ::Google::APIClient::Method.new(self.method_base, k, v)
|
||||
accu << Google::APIClient::Method.new(self.method_base, k, v)
|
||||
accu
|
||||
end
|
||||
)
|
||||
@@ -271,7 +271,7 @@ module Google
|
||||
def resources
|
||||
return @resources ||= (
|
||||
(@discovery_document['resources'] || []).inject([]) do |accu, (k, v)|
|
||||
accu << ::Google::APIClient::Resource.new(self.method_base, k, v)
|
||||
accu << Google::APIClient::Resource.new(self.method_base, k, v)
|
||||
accu
|
||||
end
|
||||
)
|
||||
@@ -284,7 +284,7 @@ module Google
|
||||
def methods
|
||||
return @methods ||= (
|
||||
(@discovery_document['methods'] || []).inject([]) do |accu, (k, v)|
|
||||
accu << ::Google::APIClient::Method.new(self.method_base, k, v)
|
||||
accu << Google::APIClient::Method.new(self.method_base, k, v)
|
||||
accu
|
||||
end
|
||||
)
|
||||
@@ -378,6 +378,14 @@ module Google
|
||||
return @discovery_document['id']
|
||||
end
|
||||
|
||||
##
|
||||
# Returns the HTTP method or 'GET' if none is specified.
|
||||
#
|
||||
# @return [String] The HTTP method that will be used in the request.
|
||||
def http_method
|
||||
return @discovery_document['httpMethod'] || 'GET'
|
||||
end
|
||||
|
||||
##
|
||||
# Returns the URI template for the method. A parameter list can be
|
||||
# used to expand this into a URI.
|
||||
@@ -465,7 +473,7 @@ module Google
|
||||
if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
|
||||
raise TypeError, "Expected Hash or Array, got #{headers.class}."
|
||||
end
|
||||
method = @discovery_document['httpMethod'] || 'GET'
|
||||
method = self.http_method
|
||||
uri = self.generate_uri(parameters)
|
||||
headers = headers.to_a if headers.kind_of?(Hash)
|
||||
return [method, uri.to_str, headers, [body]]
|
||||
|
||||
@@ -26,5 +26,15 @@ module Google
|
||||
# invalid parameter values.
|
||||
class ValidationError < StandardError
|
||||
end
|
||||
|
||||
##
|
||||
# A 4xx class HTTP error occurred.
|
||||
class ClientError < TransmissionError
|
||||
end
|
||||
|
||||
##
|
||||
# A 5xx class HTTP error occurred.
|
||||
class ServerError < TransmissionError
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,59 @@
|
||||
# Copyright 2010 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
require 'json'
|
||||
|
||||
module Google
|
||||
class APIClient
|
||||
module Parser
|
||||
def content_type(content_type)
|
||||
@@content_type_mapping ||= {}
|
||||
@@content_type_mapping[content_type] = self
|
||||
end
|
||||
|
||||
def self.match_content_type(content_type)
|
||||
# TODO(bobaman): Do this more efficiently.
|
||||
mime_type_regexp = /^([^\/]+)(?:\/([^+]+\+)?([^;]+))?(?:;.*)?$/
|
||||
if @@content_type_mapping[content_type]
|
||||
# Exact match
|
||||
return @@content_type_mapping[content_type]
|
||||
else
|
||||
media_type, extension, sub_type =
|
||||
content_type.scan(mime_type_regexp)[0]
|
||||
for pattern, parser in @@content_type_mapping
|
||||
# We want to match on subtype first
|
||||
pattern_media_type, pattern_extension, pattern_sub_type =
|
||||
pattern.scan(mime_type_regexp)[0]
|
||||
next if pattern_extension != nil
|
||||
if media_type == pattern_media_type && sub_type == pattern_sub_type
|
||||
return parser
|
||||
end
|
||||
end
|
||||
for pattern, parser in @@content_type_mapping
|
||||
# We failed to match on the subtype
|
||||
# Try to match only on the media type
|
||||
pattern_media_type, pattern_extension, pattern_sub_type =
|
||||
pattern.scan(mime_type_regexp)[0]
|
||||
next if pattern_extension != nil || pattern_sub_type != nil
|
||||
if media_type == pattern_media_type
|
||||
return parser
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
# Copyright 2010 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
require 'google/api_client/parsers/json_parser'
|
||||
|
||||
module Google
|
||||
class APIClient
|
||||
module JSON
|
||||
##
|
||||
# A module which provides a parser for error responses.
|
||||
class ErrorParser
|
||||
include Google::APIClient::JSONParser
|
||||
|
||||
matches_fields 'error'
|
||||
|
||||
def error
|
||||
return self['error']['message']
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,40 @@
|
||||
# Copyright 2010 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
require 'google/api_client/parsers/json_parser'
|
||||
|
||||
module Google
|
||||
class APIClient
|
||||
module JSON
|
||||
##
|
||||
# A module which provides a paginated parser.
|
||||
module Pagination
|
||||
def self.included(parser)
|
||||
parser.class_eval do
|
||||
include Google::APIClient::JSONParser
|
||||
end
|
||||
end
|
||||
|
||||
def next_page_token
|
||||
return self["nextPageToken"]
|
||||
end
|
||||
|
||||
def prev_page_token
|
||||
return self["prevPageToken"]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -14,27 +14,105 @@
|
||||
|
||||
|
||||
require 'json'
|
||||
require 'google/api_client/parser'
|
||||
|
||||
module Google
|
||||
class APIClient
|
||||
##
|
||||
# Provides a consistent interface by which to parse request and response
|
||||
# content.
|
||||
# TODO(mattpok): ensure floats, URLs, dates are parsed correctly
|
||||
# Provides a module which all other parsers should include.
|
||||
module JSONParser
|
||||
extend Parser
|
||||
content_type 'application/json'
|
||||
|
||||
def self.serialize(hash)
|
||||
# JSON parser used can accept arrays as well, but we will limit
|
||||
# to only allow hash to JSON string parsing to keep a simple interface
|
||||
unless hash.instance_of? Hash
|
||||
raise ArgumentError,
|
||||
"JSON generate expected a Hash but got a #{hash.class}."
|
||||
module Matcher
|
||||
def conditions
|
||||
@conditions ||= []
|
||||
end
|
||||
|
||||
def matches_kind(kind)
|
||||
self.matches_field_value(:kind, kind)
|
||||
end
|
||||
|
||||
def matches_fields(fields)
|
||||
self.conditions << [:fields, fields]
|
||||
end
|
||||
|
||||
def matches_field_value(field, value)
|
||||
self.conditions << [:field_value, field, value]
|
||||
end
|
||||
return JSON.generate(hash)
|
||||
end
|
||||
|
||||
def self.parse(json_string)
|
||||
return JSON.parse(json_string)
|
||||
def self.parsers
|
||||
@parsers ||= []
|
||||
end
|
||||
|
||||
##
|
||||
# This method ensures that all parsers auto-register themselves.
|
||||
def self.included(parser)
|
||||
self.parsers << parser
|
||||
parser.extend(Matcher)
|
||||
end
|
||||
|
||||
def initialize(data)
|
||||
@data = data.kind_of?(Hash) ? data : ::JSON.parse(data)
|
||||
end
|
||||
|
||||
def [](key)
|
||||
return self.json[key]
|
||||
end
|
||||
|
||||
def json
|
||||
if @data
|
||||
data = @data
|
||||
elsif self.respond_to?(:data)
|
||||
data = self.data
|
||||
else
|
||||
raise TypeError, "Parser did not provide access to raw data."
|
||||
end
|
||||
return data
|
||||
end
|
||||
|
||||
##
|
||||
# Matches a parser to the data.
|
||||
def self.match(data)
|
||||
for parser in self.parsers
|
||||
conditions_met = true
|
||||
for condition in (parser.conditions.sort_by { |c| c.size }).reverse
|
||||
condition_type, *params = condition
|
||||
case condition_type
|
||||
when :fields
|
||||
for field in params
|
||||
if !data.has_key?(field)
|
||||
conditions_met = false
|
||||
break
|
||||
end
|
||||
end
|
||||
when :field_values
|
||||
field, value = params
|
||||
if data[field] != value
|
||||
conditions_met = false
|
||||
break
|
||||
end
|
||||
else
|
||||
raise ArgumentError, "Unknown condition type: #{condition_type}"
|
||||
end
|
||||
break if !conditions_met
|
||||
end
|
||||
if conditions_met
|
||||
return parser
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
def self.parse(json)
|
||||
data = json.kind_of?(Hash) ? json : ::JSON.parse(json)
|
||||
parser = self.match(data)
|
||||
if parser
|
||||
return parser.new(data)
|
||||
else
|
||||
return data
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
# Copyright 2010 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
require 'stringio'
|
||||
require 'addressable/uri'
|
||||
require 'google/api_client/discovery'
|
||||
|
||||
module Google
|
||||
class APIClient
|
||||
class Reference
|
||||
def initialize(options={})
|
||||
# We only need this to do lookups on method ID String values
|
||||
# It's optional, but method ID lookups will fail if the client is
|
||||
# omitted.
|
||||
@client = options[:client]
|
||||
@version = options[:version] || 'v1'
|
||||
|
||||
self.api_method = options[:api_method]
|
||||
self.parameters = options[:parameters] || {}
|
||||
self.headers = options[:headers] || []
|
||||
if options[:body]
|
||||
self.body = options[:body]
|
||||
elsif options[:merged_body]
|
||||
self.merged_body = options[:merged_body]
|
||||
else
|
||||
self.merged_body = ''
|
||||
end
|
||||
unless self.api_method
|
||||
self.http_method = options[:http_method] || 'GET'
|
||||
self.uri = options[:uri]
|
||||
end
|
||||
end
|
||||
|
||||
def api_method
|
||||
return @api_method
|
||||
end
|
||||
|
||||
def api_method=(new_api_method)
|
||||
if new_api_method.kind_of?(Google::APIClient::Method) ||
|
||||
new_api_method == nil
|
||||
@api_method = new_api_method
|
||||
elsif new_api_method.respond_to?(:to_str) ||
|
||||
new_api_method.kind_of?(Symbol)
|
||||
unless @client
|
||||
raise ArgumentError,
|
||||
"API method lookup impossible without client instance."
|
||||
end
|
||||
new_api_method = new_api_method.to_s
|
||||
# This method of guessing the API is unreliable. This will fail for
|
||||
# APIs where the first segment of the RPC name does not match the
|
||||
# service name. However, this is a fallback mechanism anyway.
|
||||
# Developers should be passing in a reference to the method, rather
|
||||
# than passing in a string or symbol. This should raise an error
|
||||
# in the case of a mismatch.
|
||||
api = new_api_method[/^([^.]+)\./, 1]
|
||||
@api_method = @client.discovered_method(
|
||||
new_api_method, api, @version
|
||||
)
|
||||
if @api_method
|
||||
# Ditch the client reference, we won't need it again.
|
||||
@client = nil
|
||||
else
|
||||
raise ArgumentError, "API method could not be found."
|
||||
end
|
||||
else
|
||||
raise TypeError,
|
||||
"Expected Google::APIClient::Method, got #{new_api_method.class}."
|
||||
end
|
||||
end
|
||||
|
||||
def parameters
|
||||
return @parameters
|
||||
end
|
||||
|
||||
def parameters=(new_parameters)
|
||||
# No type-checking needed, the Method class handles this.
|
||||
@parameters = new_parameters
|
||||
end
|
||||
|
||||
def body
|
||||
return @body
|
||||
end
|
||||
|
||||
def body=(new_body)
|
||||
if new_body.respond_to?(:each)
|
||||
@body = new_body
|
||||
else
|
||||
raise TypeError, "Expected body to respond to :each."
|
||||
end
|
||||
end
|
||||
|
||||
def merged_body
|
||||
return (self.body.inject(StringIO.new) do |accu, chunk|
|
||||
accu.write(chunk)
|
||||
accu
|
||||
end).string
|
||||
end
|
||||
|
||||
def merged_body=(new_merged_body)
|
||||
if new_merged_body.respond_to?(:string)
|
||||
new_merged_body = new_merged_body.string
|
||||
elsif new_merged_body.respond_to?(:to_str)
|
||||
new_merged_body = new_merged_body.to_str
|
||||
else
|
||||
raise TypeError,
|
||||
"Expected String or StringIO, got #{new_merged_body.class}."
|
||||
end
|
||||
self.body = [new_merged_body]
|
||||
end
|
||||
|
||||
def headers
|
||||
return @headers ||= []
|
||||
end
|
||||
|
||||
def headers=(new_headers)
|
||||
if new_headers.kind_of?(Array) || new_headers.kind_of?(Hash)
|
||||
@headers = new_headers
|
||||
else
|
||||
raise TypeError, "Expected Hash or Array, got #{new_headers.class}."
|
||||
end
|
||||
end
|
||||
|
||||
def http_method
|
||||
return @http_method ||= self.api_method.http_method
|
||||
end
|
||||
|
||||
def http_method=(new_http_method)
|
||||
if new_http_method.kind_of?(Symbol)
|
||||
@http_method = new_http_method.to_s.upcase
|
||||
elsif new_http_method.respond_to?(:to_str)
|
||||
@http_method = new_http_method.to_str.upcase
|
||||
else
|
||||
raise TypeError,
|
||||
"Expected String or Symbol, got #{new_http_method.class}."
|
||||
end
|
||||
end
|
||||
|
||||
def uri
|
||||
return @uri ||= self.api_method.generate_uri(self.parameters)
|
||||
end
|
||||
|
||||
def uri=(new_uri)
|
||||
@uri = Addressable::URI.parse(new_uri)
|
||||
end
|
||||
|
||||
def to_request
|
||||
if self.api_method
|
||||
return self.api_method.generate_request(
|
||||
self.parameters, self.merged_body, self.headers
|
||||
)
|
||||
else
|
||||
return [self.http_method, self.uri, self.headers, self.body]
|
||||
end
|
||||
end
|
||||
|
||||
def to_hash
|
||||
options = {}
|
||||
if self.api_method
|
||||
options[:api_method] = self.api_method
|
||||
options[:parameters] = self.parameters
|
||||
else
|
||||
options[:http_method] = self.http_method
|
||||
options[:uri] = self.uri
|
||||
end
|
||||
options[:headers] = self.headers
|
||||
options[:body] = self.body
|
||||
return options
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,116 @@
|
||||
# Copyright 2010 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
require 'google/api_client/parsers/json_parser'
|
||||
|
||||
module Google
|
||||
class APIClient
|
||||
##
|
||||
# This class wraps a result returned by an API call.
|
||||
class Result
|
||||
def initialize(reference, request, response)
|
||||
@reference = reference
|
||||
@request = request
|
||||
@response = response
|
||||
end
|
||||
|
||||
attr_reader :reference
|
||||
|
||||
attr_reader :request
|
||||
|
||||
attr_reader :response
|
||||
|
||||
def status
|
||||
return @response[0]
|
||||
end
|
||||
|
||||
def headers
|
||||
return @response[1]
|
||||
end
|
||||
|
||||
def body
|
||||
return @body ||= (begin
|
||||
response_body = @response[2]
|
||||
merged_body = (response_body.inject(StringIO.new) do |accu, chunk|
|
||||
accu.write(chunk)
|
||||
accu
|
||||
end).string
|
||||
end)
|
||||
end
|
||||
|
||||
def data
|
||||
return @data ||= (begin
|
||||
_, content_type = self.headers.detect do |h, v|
|
||||
h.downcase == 'Content-Type'.downcase
|
||||
end
|
||||
parser_type =
|
||||
Google::APIClient::Parser.match_content_type(content_type)
|
||||
parser_type.parse(self.body)
|
||||
end)
|
||||
end
|
||||
|
||||
def pagination_type
|
||||
return :token
|
||||
end
|
||||
|
||||
def page_token_param
|
||||
return "pageToken"
|
||||
end
|
||||
|
||||
def next_page_token
|
||||
if self.data.respond_to?(:next_page_token)
|
||||
return self.data.next_page_token
|
||||
elsif self.data.respond_to?(:[])
|
||||
return self.data["nextPageToken"]
|
||||
else
|
||||
raise TypeError, "Data object did not respond to #next_page_token."
|
||||
end
|
||||
end
|
||||
|
||||
def next_page
|
||||
merged_parameters = Hash[self.reference.parameters].merge({
|
||||
self.page_token_param => self.next_page_token
|
||||
})
|
||||
# Because References can be coerced to Hashes, we can merge them,
|
||||
# preserving all context except the API method parameters that we're
|
||||
# using for pagination.
|
||||
return Google::APIClient::Reference.new(
|
||||
Hash[self.reference].merge(:parameters => merged_parameters)
|
||||
)
|
||||
end
|
||||
|
||||
def prev_page_token
|
||||
if self.data.respond_to?(:prev_page_token)
|
||||
return self.data.prev_page_token
|
||||
elsif self.data.respond_to?(:[])
|
||||
return self.data["prevPageToken"]
|
||||
else
|
||||
raise TypeError, "Data object did not respond to #next_page_token."
|
||||
end
|
||||
end
|
||||
|
||||
def prev_page
|
||||
merged_parameters = Hash[self.reference.parameters].merge({
|
||||
self.page_token_param => self.prev_page_token
|
||||
})
|
||||
# Because References can be coerced to Hashes, we can merge them,
|
||||
# preserving all context except the API method parameters that we're
|
||||
# using for pagination.
|
||||
return Google::APIClient::Reference.new(
|
||||
Hash[self.reference].merge(:parameters => merged_parameters)
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -16,8 +16,8 @@
|
||||
module Google
|
||||
class APIClient
|
||||
module VERSION
|
||||
MAJOR = 0
|
||||
MINOR = 2
|
||||
MAJOR = 1
|
||||
MINOR = 0
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
|
||||
Reference in new issue
Block a user