promisify gun

This commit is contained in:
Daniel Lugo 2020-01-25 14:59:32 -04:00
parent 267373a787
commit 5f2ef409c2
4 changed files with 67 additions and 5 deletions

View file

@ -31,14 +31,14 @@ export interface Soul {
put: Primitive | null | object | undefined
}
export interface GUNNode {
export interface GUNNodeBase {
_: Soul
get(key: string): GUNNode
map(): GUNNode
put(data: ValidDataValue | GUNNode, cb?: Callback): GUNNode
on(this: GUNNode, cb: Listener): void
once(this: GUNNode, cb?: Listener): GUNNode
set(data: ValidDataValue | GUNNode, cb?: Callback): GUNNode
off(): void
user(): UserGUNNode
user(epub: string): GUNNode
@ -47,6 +47,12 @@ export interface GUNNode {
then<T>(cb: (v: ListenerData) => T): Promise<ListenerData>
}
export interface GUNNode extends GUNNodeBase {
get(key: string): GUNNode
put(data: ValidDataValue | GUNNode, cb?: Callback): GUNNode
set(data: ValidDataValue | GUNNode, cb?: Callback): GUNNode
}
export interface CreateAck {
pub: string | undefined
err: string | undefined

View file

@ -0,0 +1,8 @@
/** @format */
import { GUNNode, GUNNodeBase, ValidDataValue } from '../SimpleGUN'
export interface PGUNNode extends GUNNodeBase {
get(key: string): PGUNNode
put(data: ValidDataValue | GUNNode): Promise<void>
set(data: ValidDataValue | GUNNode): Promise<void>
}

View file

@ -291,5 +291,6 @@ module.exports = {
recipientToOutgoingID,
reqWasAccepted,
currHandshakeAddress,
tryAndWait
tryAndWait,
promisifyGunNode: require('./promisifygun')
}

View file

@ -0,0 +1,47 @@
/**
* @format
* @typedef {import("../SimpleGUN").ValidDataValue} ValidDataValue
* @typedef {import('../SimpleGUN').GUNNode} GUNNode
* @typedef {import('./PGUNNode').PGUNNode} PGUNNode
*/
/**
* @param {GUNNode} node
* @returns {PGUNNode}
*/
const promisify = node => {
const oldPut = node.put.bind(node)
const oldSet = node.set.bind(node)
const oldGet = node.get.bind(node)
const _pnode = /** @type {unknown} */ (node)
const pnode = /** @type {PGUNNode} */ (_pnode)
pnode.put = data =>
new Promise((res, rej) => {
oldPut(data, ack => {
if (ack.err) {
rej(new Error(ack.err))
} else {
res()
}
})
})
pnode.set = data =>
new Promise((res, rej) => {
oldSet(data, ack => {
if (ack.err) {
rej(new Error(ack.err))
} else {
res()
}
})
})
pnode.get = key => promisify(oldGet(key))
return pnode
}
module.exports = promisify