Class: HasHelpers::Cards::RemoteRoles

Inherits:
Object
  • Object
show all
Defined in:
lib/has_helpers/cards/remote_roles.rb

Constant Summary collapse

CAPABILITY =
"roles:read"
GET_ROLE =
<<~GQL
  query Role($id: ID!) { role(id: $id) { id name organizationId } }
GQL
LIST_ROLES =
<<~GQL
  query Roles($organizationId: ID) { roles(organizationId: $organizationId) { id name organizationId } }
GQL

Instance Method Summary collapse

Constructor Details

#initialize(config: HasHelpers::Cards.config, cache: nil, client: nil) ⇒ RemoteRoles

Returns a new instance of RemoteRoles.



16
17
18
19
20
21
22
23
24
# File 'lib/has_helpers/cards/remote_roles.rb', line 16

def initialize(config: HasHelpers::Cards.config, cache: nil, client: nil)
  @config = config
  @cache = cache || Cache.new(redis: config.redis)
  @client = client || HasHelpers::ServiceTrust::GraphQLClient.new(
    audience: config.audience,
    base_url: config.base_url,
    path: config.path
  )
end

Instance Method Details

#all(force: false, organization_id: nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/has_helpers/cards/remote_roles.rb', line 37

def all(force: false, organization_id: nil)
  cache_key = organization_id.present? ? "roles:all:org=#{organization_id}" : "roles:all"
  payload = cache.fetch(cache_key, ttl: config.cache_ttl, stale_grace: config.cache_stale_grace, force: force) do
    variables = organization_id.present? ? { organizationId: organization_id } : {}
    result = client.query(LIST_ROLES, variables: variables, capability: CAPABILITY)
    raise FetchError, error_message(result, "roles list") unless result.success? && result.data

    result.data["roles"] || []
  end
  payload.map { |hash| build(hash) }
end

#find(id, force: false) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/has_helpers/cards/remote_roles.rb', line 26

def find(id, force: false)
  payload = cache.fetch("role:#{id}", ttl: config.cache_ttl, stale_grace: config.cache_stale_grace, force: force) do
    result = client.query(GET_ROLE, variables: { id: id }, capability: CAPABILITY)
    raise FetchError, error_message(result, "role #{id}") unless result.success?
    raise NotFoundError, id unless result.data && result.data["role"]

    result.data["role"]
  end
  build(payload)
end

#where(ids: nil, force: false, organization_id: nil) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/has_helpers/cards/remote_roles.rb', line 49

def where(ids: nil, force: false, organization_id: nil)
  results = all(force: force, organization_id: organization_id)
  return results if ids.nil?

  requested = ids.map(&:to_s)
  results.select { |role| requested.include?(role.id.to_s) }
end