Class: PandaPal::ApiCall

Inherits:
PandaPalRecord show all
Defined in:
app/models/panda_pal/api_call.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode_jwt(jwt) ⇒ Object

TODO Add Rate Limiting?



7
8
9
10
# File 'app/models/panda_pal/api_call.rb', line 7

def self.decode_jwt(jwt)
  jwt_payload, jwt_header = ::JWT.decode(jwt, Rails.application.secret_key_base, true, { algorithm: 'HS256' })
  jwt_payload
end

.from_jwt(jwt) ⇒ Object



12
13
14
15
# File 'app/models/panda_pal/api_call.rb', line 12

def self.from_jwt(jwt)
  jwt = decode_jwt(jwt) if jwt.is_a?(String)
  ApiCall.find(jwt['api_call_id'])
end

Instance Method Details

#call(params, internal: false) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/models/panda_pal/api_call.rb', line 21

def call(params, internal: false)
  if !internal && uses_remaining != nil
    self.uses_remaining -= 1
    if uses_remaining <= 0
      destroy!
    else
      save!
    end
  end

  prc = eval("->(p) {
    #{logic}
  }")

  prc.call(params)
end

#call_url(host: nil, params: {}, **kwargs) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'app/models/panda_pal/api_call.rb', line 38

def call_url(host: nil, params: {}, **kwargs)
  func_params = logic.scan(/\bp\[:(\w+)\]/).flatten
  phash = {}
  func_params.each.with_index do |p, i|
    phash[p.to_sym] = params[p.to_sym] || "TODO"
  end

  PandaPal::Engine.routes.url_helpers.call_logic_url(self, token: jwt_token(**kwargs), only_path: !host, host: host, **phash, format: nil)
end

#jwt_token(expiration: self.expiration) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'app/models/panda_pal/api_call.rb', line 48

def jwt_token(expiration: self.expiration)
  payload = {
    api_call_id: id,
    organization_id: Organization.current&.id,
  }
  if expiration.present?
    expiration = DateTime.parse(expiration) if expiration.is_a?(String)
    payload[:exp] = expiration.to_i
  end
  ::JWT.encode(payload, Rails.application.secret_key_base, 'HS256')
end