Skip to content

Instantly share code, notes, and snippets.

@dignifiedquire
Created June 12, 2016 21:08
Show Gist options
  • Save dignifiedquire/e2bee23d0400a882062ebc1f08b2b316 to your computer and use it in GitHub Desktop.
Save dignifiedquire/e2bee23d0400a882062ebc1f08b2b316 to your computer and use it in GitHub Desktop.
class Connection extends DuplexStream {
static isConnection (conn) {
return conn && conn._stream && conn.getPeerInfo
}
constructor (stream) {
this._stream = stream
}
get stream () {
return this._stream
}
set peerInfo (info) {
this._peerInfo = info
}
getPeerInfo (cb) {
cb(null, this._peerInfo)
}
// Implement stream methods to pass through to this._stream
}
class WrappedConnection extends Connection {
static isWrappedConnection (conn) {
return conn._connection && Connection.isConnection(conn._connection)
}
constructor (conn) {
assert(Connection.isConnection(conn))
this._connection = conn
}
get stream () {
return this._connection.stream
}
set peerInfo (info) {
this._connection.peerInfo = info
}
getPeerInfo (cb) {
this._connection.getPeerInfo(cb)
}
}
class IdentifyConnection extends WrappedConnection {
static isIdentifyConnection (conn) {
return Connection.isConnection(conn) && conn._identify
}
constructor (conn) {
assert(Connection.isConnection(conn))
super(conn)
}
_identify (cb) {
}
getPeerInfo (cb) {
this._identify((err, info) => {
this.peerInfo = info
super.getPeerInfo(cb)
})
}
}
class SecioConn extends WrappedConnection {
constructor (conn) {
assert(IdentifyConnection.isIdentifyConnection(conn))
super(conn)
}
}
const listener = transport.createListener((conn) => {
const identifiedConn = new IdentifyConnection(conn)
conn.getPeerInfo(cb) // nothing as no peerInfo is set
identifiedConn.getPeerInfo(cb) // will do identify and call back with the info
const secureConn = new SecioConn(identifiedConn)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment