Skip to content

Commit

Permalink
(CredentialEngine#713) Improve fetching envelope resources
Browse files Browse the repository at this point in the history
  • Loading branch information
excelsior committed Oct 22, 2024
1 parent f8dcd32 commit b382bc7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
3 changes: 0 additions & 3 deletions app/api/v1/resources.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,6 @@ class Resources < MountableAPI
before do
authenticate_community!
end
after_validation do
find_envelope
end
get ':id', requirements: { id: /(.*)/i } do
envelope_community = EnvelopeCommunity.find_sole_by(name: community)

Expand Down
13 changes: 8 additions & 5 deletions app/services/fetch_envelope_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ class FetchEnvelopeResource

attr_reader :envelope_community, :resource_id

delegate :connection, to: ActiveRecord::Base
delegate :quote, to: :connection

def initialize(envelope_community:, resource_id:)
@envelope_community = envelope_community
@resource_id = resource_id&.downcase
Expand All @@ -19,7 +22,8 @@ def query
FROM envelope_resources
INNER JOIN envelopes
ON envelopes.id = envelope_resources.envelope_id
WHERE envelope_resources.resource_id LIKE '%#{resource_id}'
WHERE (envelope_resources.resource_id = #{quote(resource_id)}
OR envelope_resources.resource_id LIKE #{quote('%/' + resource_id)})
AND envelopes.deleted_at IS NULL
AND envelopes.envelope_community_id = #{envelope_community.id}
UNION
Expand All @@ -46,13 +50,13 @@ def query
(
SELECT processed_resource || jsonb_build_object('@context', context)
FROM resources
WHERE resource_id LIKE '%#{resource_id}'
WHERE resource_id LIKE #{quote('%' + resource_id)}
),
'{@included}',
(
SELECT COALESCE(json_agg(processed_resource), '[]'::json)
FROM resources
WHERE resource_id NOT LIKE '%#{resource_id}'
WHERE resource_id NOT LIKE #{quote('%' + resource_id)}
)::jsonb,
(SELECT COUNT(*) FROM resources) > 1
) AS resource
Expand All @@ -61,14 +65,13 @@ def query

def resource
@resource ||= begin
connection = ActiveRecord::Base.connection
result = connection.execute(query)

result.type_map = PG::BasicTypeMapForResults.new(
connection.raw_connection
)

result.first.fetch('resource')
result.first.fetch('resource') || (raise ActiveRecord::RecordNotFound)
end
end
end
8 changes: 8 additions & 0 deletions spec/api/v1/resources_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,14 @@
get "/resources/#{CGI.escape(id).upcase}"
end

context 'nonexistent ID' do
let(:id) { Faker::Lorem.characters(number: 11) }

it 'cannot retrieve the desired resource' do
expect_status(:not_found)
end
end

context 'without `id_field`' do
context 'by full ID' do
let(:id) { full_id }
Expand Down

0 comments on commit b382bc7

Please sign in to comment.