Move Customer factory/extractor to Customer

Stephen Paul Weber created

The repo's job is to get the data, constructing the object can be a factory's job.

Change summary

lib/customer.rb      |  8 ++++++++
lib/customer_repo.rb | 29 ++++++++++-------------------
2 files changed, 18 insertions(+), 19 deletions(-)

Detailed changes

lib/customer.rb 🔗

@@ -33,6 +33,14 @@ class Customer
 	               :add_btc_address, :declines, :mark_decline,
 	               :transactions
 
+	def self.extract(customer_id, jid, **kwargs)
+		Customer.new(
+			customer_id, jid,
+			plan: CustomerPlan.extract(customer_id, kwargs),
+			**kwargs.slice(:balance, :sgx, :tndetails)
+		)
+	end
+
 	def initialize(
 		customer_id,
 		jid,

lib/customer_repo.rb 🔗

@@ -38,7 +38,7 @@ class CustomerRepo
 				redis.get("jmp_customer_jid-#{customer_id}").then do |jid|
 					raise NotFound, "No jid" unless jid
 
-					[customer_id, jid]
+					[customer_id, Blather::JID.new(jid)]
 				end
 			end
 		end
@@ -56,7 +56,7 @@ class CustomerRepo
 				redis.get("jmp_customer_id-#{jid}").then do |customer_id|
 					raise NotFound, "No customer" unless customer_id
 
-					[customer_id, jid]
+					[customer_id, Blather::JID.new(jid)]
 				end
 			end
 		end
@@ -173,29 +173,20 @@ protected
 		WHERE customer_id=$1 LIMIT 1
 	SQL
 
-	def fetch_all(customer_id)
-		EMPromise.all([
-			@sgx_repo.get(customer_id).then { |sgx| { sgx: sgx } },
-			@db.query_one(SQL, customer_id, default: {}),
-			fetch_redis(customer_id)
-		]).then { |all| all.reduce(&:merge) }
-	end
-
 	def tndetails(sgx)
 		return {} unless sgx.registered?
 
 		LazyObject.new { @bandwidth_tn_repo.find(sgx.registered?.phone) || {} }
 	end
 
-	def find_inner(customer_id, jid)
-		set_user.call(customer_id: customer_id, jid: jid)
-		fetch_all(customer_id).then do |data|
-			Customer.new(
-				customer_id, Blather::JID.new(jid),
-				tndetails: tndetails(data[:sgx]),
-				plan: CustomerPlan.extract(customer_id, data),
-				**data.slice(:balance, :sgx, :tndetails)
-			)
+	def find_inner(cid, jid)
+		set_user.call(customer_id: cid, jid: jid)
+		EMPromise.all([
+			@sgx_repo.get(cid).then { |sgx| { sgx: sgx } },
+			@db.query_one(SQL, cid, default: {}),
+			fetch_redis(cid)
+		]).then { |all| all.reduce(&:merge) }.then do |data|
+			Customer.extract(cid, jid, tndetails: tndetails(data[:sgx]), **data)
 		end
 	end
 end