~singpolyma/sgx-jmp

ref: 71349efa852cc2c469492d2e34c6a1c3cb3fb6c2 sgx-jmp/lib/customer_repo.rb -rw-r--r-- 1.1 KiB
71349efaStephen Paul Weber Factor out CustomerRepo 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# frozen_string_literal: true

require_relative "customer"

class CustomerRepo
	def initialize(redis: REDIS, db: DB, braintree: BRAINTREE)
		@redis = redis
		@db = db
		@braintree = braintree
	end

	def find(customer_id)
		result = @db.query_defer(<<~SQL, [customer_id])
			SELECT COALESCE(balance,0) AS balance, plan_name, expires_at
			FROM customer_plans LEFT JOIN balances USING (customer_id)
			WHERE customer_id=$1 LIMIT 1
		SQL
		result.then do |rows|
			Customer.new(customer_id, **rows.first&.transform_keys(&:to_sym) || {})
		end
	end

	def find_by_jid(jid)
		@redis.get("jmp_customer_id-#{jid}").then do |customer_id|
			raise "No customer id" unless customer_id
			find(customer_id)
		end
	end

	def create(jid)
		@braintree.customer.create.then do |result|
			raise "Braintree customer create failed" unless result.success?
			cid = result.customer.id
			@redis.msetnx(
				"jmp_customer_id-#{jid}", cid, "jmp_customer_jid-#{cid}", jid
			).then do |redis_result|
				raise "Saving new customer to redis failed" unless redis_result == 1
				Customer.new(cid)
			end
		end
	end
end