lib/prontoforms/client.rb in prontoforms-0.2.0 vs lib/prontoforms/client.rb in prontoforms-0.3.0

- old
+ new

@@ -1,25 +1,36 @@ require 'faraday' require 'json' require 'prontoforms/resource_list' require 'prontoforms/form_space' require 'prontoforms/form_submission' +require 'prontoforms/user' module ProntoForms class Client - attr_reader :api_key_id, :api_key_secret + # @return [String] + attr_reader :api_key_id + # @return [String] + attr_reader :api_key_secret + # @param api_key_id Your ProntoForms REST API key + # @param api_key_secret Your ProntoForms REST API secret def initialize(api_key_id, api_key_secret) @api_key_id = api_key_id @api_key_secret = api_key_secret end - def self.resource(method, verb: :get, resource:, url: resource.resource_name) - # TODO: Raise error if verb is invalid - + # Defines a resource that can be retrieved in a list + # @return [nil] + # @api private + # @!macro [attach] resource_list + # @method $1 + # Retrieve a list of $2 resources + # @return [ResourceList] A ResourceList containing $2 results + def self.resource_list(method, resource, url = resource.resource_name) define_method(method) do |query: {}| - res = connection.send(verb) do |req| + res = connection.get do |req| req.url url query.each { |k, v| req.params[k] = v } end if res.success? ResourceList.new(JSON.parse(res.body), { @@ -30,12 +41,45 @@ nil end end end - resource :form_spaces, resource: FormSpace - resource :form_submissions, resource: FormSubmission + resource_list :form_spaces, FormSpace + resource_list :form_submissions, FormSubmission + # Retrieve a user by identifier + # @param id [String] The user identifier + # @return [User] A User object for the requested user + def user(id) + return nil if id.nil? + res = connection.get do |req| + req.url "users/#{id.to_s}" + end + if res.success? + data = JSON.parse(res.body) + User.new(data, self) + else + nil + end + end + + def form_submission(id) + return nil if id.nil? + res = connection.get do |req| + req.url "data/#{id.to_s}" + end + if res.success? + data = JSON.parse(res.body) + FormSubmission.new(data, self) + else + nil + end + end + + # Create a connection that can be used to execute a request against the + # ProntoForms API. + # @return [Faraday::Connection] + # @api private def connection Faraday.new(url: 'https://api.prontoforms.com/api/1.1') do |conn| conn.basic_auth(api_key_id, api_key_secret) end end