Sha256: b87eda89b08f51aafc63cd5cece3d91cae1f2872d00be0633764b1b235aa6b9c

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

require 'httparty'
require 'json'
require 'redis-namespace'
require_relative 'utils'

class Valnzbn
  class Lookup

    PRODUCTION_URL = 'https://api.business.govt.nz/services/v3/nzbn/entities/'
    SANDBOX_URL = 'https://sandbox.api.business.govt.nz/services/v3/nzbn/entities/'

    @@cache_host = nil
    @@cache_port = nil
    @@access_token = nil
    @@mode = :sandbox

    def self.access_token=(value)
      @@access_token = value
    end

    def self.mode=(value)
      @@mode = value.to_sym
    end

    def self.cache_host=(value)
      @@cache_host = value
    end

    def self.cache_port=(value)
      @@cache_port = value
    end

    def self.configure
      yield self
    end

    def self.validate(number, options = {})
      url = @@mode == :sandbox ? SANDBOX_URL : PRODUCTION_URL
      number = number.to_s.gsub(/\W/, '')

      if Valnzbn::Utils.valid_format?(number)
        cache = if @@cache_port && @@cache_host
          redis_client = Redis.new(host: @@cache_host, port: @@cache_port, db: 15)
          namespaced_redis = Redis::Namespace.new(:valnzbn_cache, redis: redis_client)

          JSON.parse(namespaced_redis.get(number) || '{}', symbolize_names: true)
        else
          {}
        end

        if cache.any? && Time.at(cache[:expires_at]) > Time.now
          cache
        else
          begin
            response = HTTParty.get("#{url}#{number}", headers: { 'Authorization' => "Bearer #{@@access_token}" }).parsed_response
            response = JSON.parse(response.to_json, symbolize_names: true)
            response[:expires_at] = (Time.now + 7200).to_i

            namespaced_redis.set(number, response.to_json) if @@cache_port && @@cache_host
            response
          rescue
            nil
          end
        end
      else
        {}
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
valnzbn-0.1.4 lib/valnzbn/lookup.rb