better handshake address event

This commit is contained in:
Daniel Lugo 2020-02-20 19:03:15 -04:00
parent 4f81b8f6b8
commit fd2c132f3e

View file

@ -156,33 +156,55 @@ const onBlacklist = (cb, user) => {
}) })
} }
/** @type {Set<(addr: string|null) => void>} */
const addressListeners = new Set()
/** @type {string|null} */
let currentAddress = null
const getHandshakeAddress = () => currentAddress
/** @param {string|null} addr */
const setAddress = addr => {
currentAddress = addr
addressListeners.forEach(l => l(currentAddress))
}
let addrSubbed = false
/** /**
* @param {(currentHandshakeAddress: string|null) => void} cb * @param {(currentHandshakeAddress: string|null) => void} cb
* @param {UserGUNNode} user * @param {UserGUNNode} user
* @returns {void} * @returns {() => void}
*/ */
const onCurrentHandshakeAddress = (cb, user) => { const onCurrentHandshakeAddress = (cb, user) => {
if (!user.is) { if (!user.is) {
throw new Error(ErrorCode.NOT_AUTH) throw new Error(ErrorCode.NOT_AUTH)
} }
const callb = debounce(cb, DEBOUNCE_WAIT_TIME) addressListeners.add(cb)
// If undefined, callback below wont be called. Let's supply null as the cb(currentAddress)
// initial value.
callb(null) if (!addrSubbed) {
addrSubbed = true
user.get(Key.CURRENT_HANDSHAKE_ADDRESS).on(addr => { user.get(Key.CURRENT_HANDSHAKE_ADDRESS).on(addr => {
if (typeof addr !== 'string') { if (typeof addr !== 'string') {
console.error('expected handshake address to be an string') console.error('expected handshake address to be an string')
callb(null) setAddress(null)
return return
} }
callb(addr) setAddress(addr)
}) })
}
return () => {
addressListeners.delete(cb)
}
} }
/** @type {Set<(dn: string|null) => void>} */ /** @type {Set<(dn: string|null) => void>} */
@ -578,5 +600,6 @@ module.exports = {
onSeedBackup, onSeedBackup,
onChats, onChats,
getAvatar, getAvatar,
getDisplayName getDisplayName,
getHandshakeAddress
} }