diff --git a/app/controllers/data_queries_controller.rb b/app/controllers/data_queries_controller.rb index c68eb11675..41daeda3e3 100644 --- a/app/controllers/data_queries_controller.rb +++ b/app/controllers/data_queries_controller.rb @@ -42,7 +42,6 @@ class DataQueriesController < ApplicationController query_service = QueryService.new @data_query, params[:options], @current_user result = query_service.process - - render json: result + render json: result, status: result[:code] || 200 end end diff --git a/app/services/googlesheets_query_service.rb b/app/services/googlesheets_query_service.rb index 4a42fb5340..7d8fef585a 100644 --- a/app/services/googlesheets_query_service.rb +++ b/app/services/googlesheets_query_service.rb @@ -1,5 +1,5 @@ class GooglesheetsQueryService - attr_accessor :query, :ource, :options, :source_options, :current_user + attr_accessor :query, :source, :options, :source_options, :current_user def initialize(data_query, options, source_options, current_user) @query = data_query @@ -12,28 +12,56 @@ class GooglesheetsQueryService def process operation = query.options['operation'] access_token = source_options['access_token'] + error = false if operation === 'read' + result = read_data(access_token) + + if result.code === 401 + refresh_access_token + result = read_data(access_token) + end + + if result.code === 200 + + headers = result['values'][0] + values = result['values'][1..] + + data = [] + values.each do |value| + row = {} + headers.each_with_index do |header, index| + row[header] = value[index] + end + parsed_values << row + end + + else + error = true + data = result["error"] + end + end + + if error + { status: 'error', code: 500, message: data["message"], data: data } + else + { status: 'success', data: data } + end + end + + private + def read_data(access_token) spreadsheet_id = query.options['spreadsheet_id'] sheet = query.options['sheet'] result = HTTParty.get("https://sheets.googleapis.com/v4/spreadsheets/#{spreadsheet_id}/values/#{sheet}!A1:V101", - headers: { 'Content-Type': - 'application/json', "Authorization": "Bearer #{access_token}" }) + headers: { 'Content-Type': + 'application/json', "Authorization": "Bearer #{access_token}" }) - headers = result['values'][0] - values = result['values'][1..] - - parsed_values = [] - values.each do |value| - row = {} - headers.each_with_index do |header, index| - row[header] = value[index] - end - parsed_values << row - end + result end - { status: 'success', data: parsed_values } - end + def refresh_access_token + + end end