customer_repo.rb

 1# frozen_string_literal: true
 2
 3require_relative "customer"
 4
 5class CustomerRepo
 6	def initialize(redis: REDIS, db: DB, braintree: BRAINTREE)
 7		@redis = redis
 8		@db = db
 9		@braintree = braintree
10	end
11
12	def find(customer_id)
13		result = @db.query_defer(<<~SQL, [customer_id])
14			SELECT COALESCE(balance,0) AS balance, plan_name, expires_at
15			FROM customer_plans LEFT JOIN balances USING (customer_id)
16			WHERE customer_id=$1 LIMIT 1
17		SQL
18		result.then do |rows|
19			Customer.new(customer_id, **rows.first&.transform_keys(&:to_sym) || {})
20		end
21	end
22
23	def find_by_jid(jid)
24		@redis.get("jmp_customer_id-#{jid}").then do |customer_id|
25			raise "No customer id" unless customer_id
26			find(customer_id)
27		end
28	end
29
30	def create(jid)
31		@braintree.customer.create.then do |result|
32			raise "Braintree customer create failed" unless result.success?
33			cid = result.customer.id
34			@redis.msetnx(
35				"jmp_customer_id-#{jid}", cid, "jmp_customer_jid-#{cid}", jid
36			).then do |redis_result|
37				raise "Saving new customer to redis failed" unless redis_result == 1
38				Customer.new(cid)
39			end
40		end
41	end
42end