registration_repo.rb

 1# frozen_string_literal: true
 2
 3require 'lazy_object'
 4
 5class RegistrationRepo
 6	class Conflict < StandardError; end
 7
 8	def initialize(redis: LazyObject.new { REDIS })
 9		@redis = redis
10	end
11
12	def find(jid)
13		REDIS.lrange(cred_key(jid), 0, 3)
14	end
15
16	def find_jid(tel)
17		REDIS.get(jid_key(tel))
18	end
19
20	def put(jid, *creds)
21		tel = creds.last
22
23		EMPromise.all([
24			find(jid),
25			REDIS.set(
26				jid_key(tel),
27				Blather::JID.new(jid).stripped.to_s,
28				"NX", "GET"
29			)
30		]).then { |(oldcreds, oldjid)|
31			if oldjid && oldjid != jid.stripped.to_s
32				raise Conflict, "Another user exists for #{tel}"
33			end
34
35			if !oldcreds.empty? && oldcreds != creds
36				REDIS.set(jid_key(tel), oldjid).then do
37					raise Conflict, "Another user exists for #{jid}"
38				end
39			end
40		}.then {
41			REDIS.rpush(cred_key(jid), *creds)
42		}
43	end
44
45protected
46
47	def cred_key(jid)
48		"catapult_cred-#{Blather::JID.new(jid).stripped}"
49	end
50
51	def jid_key(tel)
52		"catapult_jid-#{tel}"
53	end
54end