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
45 def delete(jid)
46 find(jid).then { |creds|
47 REDIS.del(
48 cred_key(jid),
49 jid_key(creds.last)
50 )
51 }
52 end
53
54protected
55
56 def cred_key(jid)
57 "catapult_cred-#{Blather::JID.new(jid).stripped}"
58 end
59
60 def jid_key(tel)
61 "catapult_jid-#{tel}"
62 end
63end