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.exists(jid_key(tel))
26 ]).then { |(oldcreds, oldjid)|
27 if oldjid == "1" || (!oldcreds.empty? && oldcreds != creds)
28 raise Conflict, "Another user exists for #{tel}"
29 end
30
31 EMPromise.all([
32 REDIS.set(
33 jid_key(tel),
34 Blather::JID.new(jid).stripped.to_s,
35 "NX"
36 ),
37 REDIS.rpush(cred_key(jid), *creds)
38 ])
39 }
40 end
41
42 def delete(jid)
43 find(jid).then { |creds|
44 REDIS.del(
45 cred_key(jid),
46 jid_key(creds.last)
47 )
48 }
49 end
50
51protected
52
53 def cred_key(jid)
54 "catapult_cred-#{Blather::JID.new(jid).stripped}"
55 end
56
57 def jid_key(tel)
58 "catapult_jid-#{tel}"
59 end
60end