Module: Grist::Rest
- Included in:
- Type::Base, Type::Column
- Defined in:
- lib/grist/rest.rb
Instance Method Summary collapse
- #create(data) ⇒ Object
- #delete ⇒ Object
- #get(id) ⇒ Object
- #list(params = {}) ⇒ Object
- #path ⇒ Object
- #request(method, endpoint, params = {}) ⇒ Object
- #update(data) ⇒ Object
Instance Method Details
#create(data) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/grist/rest.rb', line 52 def create(data) grist_res = request(:post, path, data) puts "Creating #{path} with data: #{data}" puts puts grist_res.inspect return unless grist_res.success? data.each_key do |key| instance_variable_set("@#{key}", data[key]) end self end |
#delete ⇒ Object
77 78 79 80 81 82 83 84 85 |
# File 'lib/grist/rest.rb', line 77 def delete id = instance_variable_get("@id") grist_res = request(:delete, "#{path}/#{id}") return unless grist_res.success? instance_variable_set("@deleted", true) self end |
#get(id) ⇒ Object
48 49 50 |
# File 'lib/grist/rest.rb', line 48 def get(id) request(:get, "#{path}/#{id}") end |
#list(params = {}) ⇒ Object
44 45 46 |
# File 'lib/grist/rest.rb', line 44 def list(params = {}) request(:get, path, params) end |
#path ⇒ Object
40 41 42 |
# File 'lib/grist/rest.rb', line 40 def path self.class::PATH end |
#request(method, endpoint, params = {}) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/grist/rest.rb', line 5 def request(method, endpoint, params = {}) uri = URI("#{::Grist.base_api_url}#{endpoint}") uri.query = URI.encode_www_form(params) if method == :get http = ::Net::HTTP.new(uri.host, uri.port) http.use_ssl = !::Grist.localhost? request = ::Net::HTTP.const_get(method.capitalize).new(uri) request["Authorization"] = ::Grist.token_auth request["Content-Type"] = "application/json" request.body = params.to_json unless method == :get response = http.request(request) raise InvalidApiKey, "Invalid API key" if response.is_a?(Net::) raise NotFound, "Resource not found at : #{request.uri}" if response.is_a?(Net::HTTPNotFound) data = response_body(response.body) Grist::Response.new(data: data, code: response.code) rescue Net::OpenTimeout, Net::ReadTimeout, SocketError => e res = Grist::Response.new(code: response&.code, error: "Grist endpoint is unreachable at #{request.uri}", type: e.class) res.log_error raise NetworkError, res.print_error rescue APIError => e res = Grist::Response.new(code: response&.code, error: e., type: e.class) res.log_error res rescue StandardError, Grist::NotFound => e res = Grist::Response.new(code: response&.code, error: e., type: e.class) res.log_error res end |
#update(data) ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/grist/rest.rb', line 65 def update(data) id = instance_variable_get("@id") grist_res = request(:patch, "#{path}/#{id}", data) return unless grist_res.success? data.each_key do |key| instance_variable_set("@#{key}", data[key]) end self end |