Skip to content

Commit

Permalink
Merge PR #231 from TreinaDev/refactor/api-services
Browse files Browse the repository at this point in the history
Refactor/api services
  • Loading branch information
eliseuramos93 authored Feb 15, 2024
2 parents 2e3f9ea + 74b3e9b commit 1ad9d72
Show file tree
Hide file tree
Showing 18 changed files with 191 additions and 134 deletions.
11 changes: 5 additions & 6 deletions app/controllers/api/v1/projects_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module Api
module V1
class ProjectsController < ApiController
def index
response = Faraday.get('http://localhost:3000/api/v1/projects')
response = ProjectsService::ColaBoraApiGetProjects.send
if response.status == 200
projects = JSON.parse(response.body)
render status: :ok, json: projects.as_json
Expand All @@ -13,9 +13,9 @@ def index
end

def request_invitation
data = proposal_params.as_json
connection = Faraday.new(url: 'http://localhost:3000', params: data)
response = connection.post('api/v1/proposals')
invitation_request_id = proposal_params.fetch('invitation_request_id').to_i
invitation_request = InvitationRequest.find(invitation_request_id)
response = InvitationRequestService::ColaBoraInvitationRequestPost.send(invitation_request)

if response.status == 201
proposal = JSON.parse(response.body)
Expand All @@ -29,8 +29,7 @@ def request_invitation
private

def proposal_params
proposal_attributes = %i[invitation_request_id email message profile_id project_id]
params.require(:data).permit(proposal: proposal_attributes)
params.permit(:invitation_request_id)
end
end
end
Expand Down
1 change: 1 addition & 0 deletions app/controllers/projects_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def index
@invitation_request = current_user.invitation_requests.build
@invitation_requests = current_user.invitation_requests.pluck(:project_id).to_json
@invitation_requests_projects_ids = current_user.invitation_requests.pluck(:project_id)
@projects_url = Rails.configuration.portfoliorrr_api_v1.projects_url
@free_user = current_user.subscription.inactive?
end

Expand Down
3 changes: 2 additions & 1 deletion app/javascript/components/projects_vue.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export default {
invitationRequestsProjectsIds: window.invitationRequestsProjectsIds,
freeUser: window.freeUser,
errorMsg: false,
portfoliorrrProjectsApiUrl: window.portfoliorrrProjectsApiUrl,
}
},
computed:{
Expand Down Expand Up @@ -47,7 +48,7 @@ export default {
async created() {
if (!freeUser) {
try {
let response = await fetch('/api/v1/projects', { signal });
let response = await fetch(this.portfoliorrrProjectsApiUrl, { signal });
if (response.ok) {
let data = await response.json();
if (!data.message) {
Expand Down
4 changes: 3 additions & 1 deletion app/jobs/decline_invitation_job.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
class DeclineInvitationJob < ApplicationJob
PORTFOLIORRR_BASE_URL = Rails.configuration.portfoliorrr_api_v1.base_url
PORTFOLIORRR_INVITATION_URL = Rails.configuration.portfoliorrr_api_v1.invitations_url
retry_on Faraday::ConnectionFailed, Faraday::ServerError, wait: :polynomially_longer, attempts: 5 do |job|
job.arguments.first.pending!
end

def perform(invitation)
url = "http://localhost:4000/api/v1/invitations/#{invitation.colabora_invitation_id}"
url = "#{PORTFOLIORRR_BASE_URL}#{PORTFOLIORRR_INVITATION_URL}#{invitation.colabora_invitation_id}"
Faraday.new { |faraday| faraday.response :raise_error }.patch(url)
invitation.declined!
rescue Faraday::ResourceNotFound, Faraday::ConflictError
Expand Down
6 changes: 4 additions & 2 deletions app/jobs/request_invitation_job.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
class RequestInvitationJob < ApplicationJob
PORTFOLIORRR_BASE_URL = Rails.configuration.portfoliorrr_api_v1.base_url
PORTFOLIORRRR_REQUEST_INVITATION_URL = Rails.configuration.portfoliorrr_api_v1.request_invitation_url
queue_as :default
retry_on Exceptions::PortfoliorrrAPIOffline, wait: 1.hour, attempts: :unlimited
retry_on Exceptions::ColaBoraAPIOffline, wait: 1.hour, attempts: 5 do |job, _error|
job.arguments.first[:invitation_request].aborted!
end

def perform(invitation_request:)
data = invitation_request.create_json_for_proposal_request
response = Faraday.new(url: 'http://localhost:4000', params: data).get('/api/v1/projects/request_invitation')
data = { invitation_request_id: invitation_request.id }.as_json
response = Faraday.new(url: PORTFOLIORRR_BASE_URL, params: data).get(PORTFOLIORRRR_REQUEST_INVITATION_URL)
return raise Exceptions::PortfoliorrrAPIOffline if response.status == :internal_server_error

invitation_request.process_colabora_api_response(response)
Expand Down
8 changes: 0 additions & 8 deletions app/models/invitation_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,6 @@ def process_colabora_api_response(response)
end
end

def create_json_for_proposal_request
{ data: { proposal: { invitation_request_id: id,
project_id:,
profile_id: profile.id,
email: profile.email,
message: } } }.as_json
end

private

def json_treated_response(response)
Expand Down
54 changes: 29 additions & 25 deletions app/services/invitation_request_service.rb
Original file line number Diff line number Diff line change
@@ -1,40 +1,44 @@
module InvitationRequestService
COLABORA_PROJECTS_URL = 'http://localhost:3000/api/v1/projects'.freeze
COLABORA_INVITATIONS_BASE_URL = 'http://localhost:3000/api/v1/invitations'.freeze
include ProjectsService

class ColaboraProject
def self.send
@response = Faraday.get(COLABORA_PROJECTS_URL)
return build_projects if @response.success?

raise StandardError
end

class << self
private

def build_projects
projects = JSON.parse(@response.body, symbolize_names: true)
projects.map do |project|
Project.new(id: project[:id],
title: project[:title],
description: project[:description],
category: project[:category])
end
end
end
end
COLABORA_BASE_URL = Rails.configuration.colabora_api_v1.base_url
COLABORA_API_V1_PROJECTS_URL = Rails.configuration.colabora_api_v1.projects_url
COLABORA_API_V1_PROPOSALS_URL = Rails.configuration.colabora_api_v1.proposals_url

class InvitationRequest
def self.send(requests)
return [] if requests.empty?

projects = ColaboraProject.send
projects = ProjectsService::ColaBoraProject.send

requests.map do |request|
project = projects.find { |proj| proj.id == request.project_id }
InvitationRequestInfo.new(invitation_request: request, project:)
end
end
end

class ColaBoraInvitationRequestPost
def self.send(invitation_request)
@invitation_request = invitation_request
post_connection

@response
end

class << self
private

def build_invitation_request_params(invitation_request)
{ 'proposal': { 'invitation_request_id': invitation_request.id, 'email': invitation_request.profile.email,
'message': invitation_request.message, 'profile_id': invitation_request.profile.id,
'project_id': invitation_request.project_id } }.as_json
end

def post_connection
url = "#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROPOSALS_URL}"
@response = Faraday.post(url, build_invitation_request_params(@invitation_request))
end
end
end
end
34 changes: 34 additions & 0 deletions app/services/projects_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module ProjectsService
COLABORA_BASE_URL = Rails.configuration.colabora_api_v1.base_url
COLABORA_API_V1_PROJECTS_URL = Rails.configuration.colabora_api_v1.projects_url

class ColaBoraProject
def self.send
@response = ColaBoraApiGetProjects.send
return build_projects if @response.success?

raise StandardError
end

class << self
private

def build_projects
projects = JSON.parse(@response.body, symbolize_names: true)
projects.map do |project|
Project.new(id: project[:id],
title: project[:title],
description: project[:description],
category: project[:category])
end
end
end
end

class ColaBoraApiGetProjects
def self.send
url = "#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}"
Faraday.get(url)
end
end
end
2 changes: 1 addition & 1 deletion app/views/invitations/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<% if @invitation.pending? %>
<div class="btn-group">
<div>
<%= link_to t('accept_btn'), 'http://localhost:3000', class: 'btn btn-primary me-4' %>
<%= link_to t('accept_btn'), Rails.configuration.colabora_api_v1.base_url, class: 'btn btn-primary me-4' %>
</div>
<div>
<%= button_to t('decline_btn'), decline_invitation_path(@invitation), method: :patch, class: 'btn btn-secondary' %>
Expand Down
1 change: 1 addition & 0 deletions app/views/projects/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
</div>

<script>
var portfoliorrrProjectsApiUrl = '<%= @projects_url %>'
var invitationRequestsProjectsIds = <%= @invitation_requests_projects_ids %>
var freeUser = <%= @free_user %>
</script>
6 changes: 6 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,11 @@ class Application < Rails::Application

# Don't generate system test files.
config.generators.system_tests = nil

# ColaBora API configurations
config.colabora_api_v1 = config_for(:colabora_api_v1)

# Portfoliorrr API configurations
config.portfoliorrr_api_v1 = config_for(:portfoliorrr_api_v1)
end
end
9 changes: 9 additions & 0 deletions config/colabora_api_v1.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
development:
base_url: 'http://localhost:3000'
projects_url: '/api/v1/projects'
proposals_url: '/api/v1/proposals'

test:
base_url: 'http://localhost:3000'
projects_url: '/api/v1/projects'
proposals_url: '/api/v1/proposals'
11 changes: 11 additions & 0 deletions config/portfoliorrr_api_v1.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
development:
base_url: 'http://localhost:4000'
invitations_url: '/api/v1/invitations/'
request_invitation_url: '/api/v1/projects/request_invitation'
projects_url: '/api/v1/projects'

test:
base_url: 'http://localhost:4000'
invitations_url: '/api/v1/invitations/'
request_invitation_url: '/api/v1/projects/request_invitation'
projects_url: '/api/v1/projects'
30 changes: 5 additions & 25 deletions spec/jobs/request_invitation_job_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
RSpec.describe RequestInvitationJob, type: :job do
it 'altera a solicitação de convite para pending caso receba uma confirmação de sucesso do Cola?Bora!' do
invitation_request = create(:invitation_request)
invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id,
project_id: invitation_request.project_id,
profile_id: invitation_request.profile.id,
email: invitation_request.profile.email,
message: invitation_request.message } } }.as_json
invitation_request_params = { invitation_request_id: invitation_request.id }.as_json

json_proposal_response = File.read(Rails.root.join('./spec/support/json/proposal_201.json'))
fake_portfoliorrr_response = double('faraday_response', status: :ok, body: json_proposal_response)
Expand All @@ -30,11 +26,7 @@

it 'enfileira um novo job caso receba um aviso de erro no servidor do Cola?Bora!' do
invitation_request = create(:invitation_request)
invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id,
project_id: invitation_request.project_id,
profile_id: invitation_request.profile.id,
email: invitation_request.profile.email,
message: invitation_request.message } } }.as_json
invitation_request_params = { invitation_request_id: invitation_request.id }.as_json

fake_colabora_response_body = { 'errors': ['Erro interno de servidor.'] }.as_json
fake_portfoliorrr_response = double('faraday_response', status: :ok, body: fake_colabora_response_body)
Expand All @@ -57,11 +49,7 @@

it 'altera a solicitação de convite para error caso receba um aviso de erro do Cola?Bora!' do
invitation_request = create(:invitation_request)
invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id,
project_id: invitation_request.project_id,
profile_id: invitation_request.profile.id,
email: invitation_request.profile.email,
message: invitation_request.message } } }.as_json
invitation_request_params = { invitation_request_id: invitation_request.id }.as_json

fake_colabora_response_body = { 'errors': ['Usuário já faz parte deste projeto'] }.as_json
fake_portfoliorrr_response = double('faraday_response', status: :ok, body: fake_colabora_response_body)
Expand All @@ -84,11 +72,7 @@

it 'altera a solicitação de convite para aborted se receber pela quinta vez um erro da API do Cola?Bora!' do
invitation_request = create(:invitation_request)
invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id,
project_id: invitation_request.project_id,
profile_id: invitation_request.profile.id,
email: invitation_request.profile.email,
message: invitation_request.message } } }.as_json
invitation_request_params = { invitation_request_id: invitation_request.id }.as_json

fake_colabora_response_body = { 'errors': ['Erro interno de servidor.'] }.as_json
fake_portfoliorrr_response = double('faraday_response', status: :ok, body: fake_colabora_response_body)
Expand All @@ -114,11 +98,7 @@

it 'gera uma nova tentativa caso a API do Portfoliorrr esteja fora do ar, sem limite de tentativas' do
invitation_request = create(:invitation_request)
invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id,
project_id: invitation_request.project_id,
profile_id: invitation_request.profile.id,
email: invitation_request.profile.email,
message: invitation_request.message } } }.as_json
invitation_request_params = { invitation_request_id: invitation_request.id }.as_json

fake_response_body = { 'error': 'Houve um erro interno no servidor ao processar sua solicitação.' }.as_json
fake_portfoliorrr_response = double('faraday_response', status: :internal_server_error, body: fake_response_body)
Expand Down
Loading

0 comments on commit 1ad9d72

Please sign in to comment.