refactor: use adapter class in interface-transport

License: MIT
Signed-off-by: Alan Shaw <alan.shaw@protocol.ai>
This commit is contained in:
Alan Shaw 2019-04-18 15:03:10 +01:00
parent 89ae00a0b8
commit e48fee1698
No known key found for this signature in database
GPG Key ID: AFC4442246B75B6F
2 changed files with 4 additions and 69 deletions

View File

@ -41,7 +41,6 @@
"homepage": "https://github.com/libp2p/js-libp2p-websockets#readme",
"dependencies": {
"abortable-iterator": "^2.0.0",
"async-iterator-to-pull-stream": "^1.3.0",
"class-is": "^1.1.0",
"debug": "^4.1.1",
"interface-connection": "~0.3.3",

View File

@ -1,77 +1,13 @@
'use strict'
const { Connection } = require('interface-connection')
const { Adapter } = require('interface-transport')
const withIs = require('class-is')
const toPull = require('async-iterator-to-pull-stream')
const error = require('pull-stream/sources/error')
const drain = require('pull-stream/sinks/drain')
const WebSockets = require('./')
const noop = () => {}
function callbackify (fn) {
return async function (...args) {
let cb = args.pop()
if (typeof cb !== 'function') {
args.push(cb)
cb = noop
}
let res
try {
res = await fn(...args)
} catch (err) {
return cb(err)
}
cb(null, res)
}
}
// Legacy adapter to old transport & connection interface
class WebSocketsAdapter extends WebSockets {
dial (ma, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
callback = callback || noop
const conn = new Connection()
super.dial(ma, options)
.then(socket => {
conn.setInnerConn(toPull.duplex(socket))
conn.getObservedAddrs = callbackify(socket.getObservedAddrs.bind(socket))
conn.close = callbackify(socket.close.bind(socket))
callback(null, conn)
})
.catch(err => {
conn.setInnerConn({ sink: drain(), source: error(err) })
callback(err)
})
return conn
}
createListener (options, handler) {
if (typeof options === 'function') {
handler = options
options = {}
}
const server = super.createListener(options, socket => {
const conn = new Connection(toPull.duplex(socket))
conn.getObservedAddrs = callbackify(socket.getObservedAddrs.bind(socket))
handler(conn)
})
const proxy = {
listen: callbackify(server.listen.bind(server)),
close: callbackify(server.close.bind(server)),
getAddrs: callbackify(server.getAddrs.bind(server)),
getObservedAddrs: callbackify(() => server.getObservedAddrs())
}
return new Proxy(server, { get: (_, prop) => proxy[prop] || server[prop] })
class WebSocketsAdapter extends Adapter {
constructor () {
super(new WebSockets())
}
}