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, ex: 7200) if @@cache_port && @@cache_host response rescue nil end end else {} end end end end