create() and leave()

This commit is contained in:
Daniel Lugo 2021-09-13 17:43:38 -04:00
parent f43748c96c
commit 659588cf15
3 changed files with 96 additions and 3 deletions

View file

@ -212,6 +212,7 @@ const flushPendingPuts = () => {
const forge = () => {
if (currentGun) {
currentGun.off('message', handleMsg)
currentGun.disconnect()
currentGun.kill()
}
const newGun = fork('utils/GunSmith/gun.js')
@ -515,15 +516,63 @@ function createUserReplica() {
})
})
},
create() {},
leave() {}
create(alias, pass, cb) {
lastAlias = ''
lastPass = ''
lastPair = null
/** @type {Smith.SmithMsgCreate} */
const msg = {
alias,
pass,
type: 'create'
}
/** @param {Smith.GunMsg} msg */
const _cb = msg => {
if (msg.type === 'create') {
currentGun.off('message', _cb)
const { ack } = msg
if (ack.err) {
cb(ack)
} else if (ack.pub) {
lastAlias = alias
lastPass = pass
lastPair = msg.pair
cb(ack)
} else {
throw (new Error('Auth: ack.pub undefined'))
}
}
}
currentGun.on('message', _cb)
currentGun.send(msg)
},
leave() {
lastAlias = ''
lastPass = ''
lastPair = null
/** @type {Smith.SmithMsgLeave} */
const msg = {
type: 'leave'
}
currentGun.send(msg)
}
}
return completeReplica
}
/**
* @typedef {GunT.GUNNode & { kill(): void }} RootNode
*/
/**
* @param {import('gun/types/options').IGunConstructorOptions} opts
* @returns {RootNode}
*/
const Gun = opts => {
lastOpts = opts
@ -531,7 +580,16 @@ const Gun = opts => {
// We should ideally wait for a response but we'd break the constructor's
// signature
return createReplica('$root')
return {
...createReplica('$root'),
kill() {
if (currentGun) {
currentGun.off('message', handleMsg)
currentGun.disconnect()
currentGun.kill()
}
}
}
}
module.exports = Gun

View file

@ -20,6 +20,16 @@ namespace Smith {
type: 'auth'
}
export interface SmithMsgCreate {
alias: string
pass: string
type: 'create'
}
export interface SmithMsgLeave {
type: 'leave'
}
export interface SmithMsgOn {
path: string
type: 'on'
@ -53,6 +63,8 @@ namespace Smith {
export type SmithMsg =
| SmithMsgInit
| SmithMsgAuth
| SmithMsgCreate
| SmithMsgAuth
| SmithMsgOn
| SmithMsgLoad
| SmithMsgMapOn
@ -67,6 +79,12 @@ namespace Smith {
type: 'auth'
}
export interface GunMsgCreate {
ack: GunT.CreateAck
pair: GunT.UserPair
type: 'create'
}
export interface GunMsgOn {
data: GunT.ListenerData
path: string
@ -103,6 +121,7 @@ namespace Smith {
export type GunMsg =
| GunMsgAuth
| GunMsgCreate
| GunMsgOn
| GunMsgMapOn
| GunMsgLoad

View file

@ -91,6 +91,21 @@ const handleMsg = msg => {
sendMsg(msg)
})
}
if (msg.type === 'create') {
const { alias, pass } = msg
user.create(alias, pass, ack => {
/** @type {Smith.GunMsgCreate} */
const msg = {
ack: {
err: ack.err,
pub: ack.pub
},
pair: user._.sea,
type: 'create'
}
sendMsg(msg)
})
}
if (msg.type === 'load') {
const [root, ...keys] = msg.path.split('>')
@ -209,6 +224,7 @@ const handleMsg = msg => {
err: ack.err
},
ids: msg.ids,
path: msg.path,
type: 'multiPut'
}
sendMsg(reply)