mirror of
https://github.com/fluencelabs/js-libp2p-websockets
synced 2025-04-04 23:51:15 +00:00
Not passing errors meant that failed websocket connections were being treated as successful dials.
61 lines
1.4 KiB
JavaScript
61 lines
1.4 KiB
JavaScript
'use strict'
|
|
|
|
const connect = require('pull-ws/client')
|
|
const mafmt = require('mafmt')
|
|
const includes = require('lodash.includes')
|
|
const Connection = require('interface-connection').Connection
|
|
|
|
const maToUrl = require('./ma-to-url')
|
|
const debug = require('debug')
|
|
const log = debug('libp2p:websockets:dialer')
|
|
|
|
const createListener = require('./listener')
|
|
|
|
class WebSockets {
|
|
dial (ma, options, callback) {
|
|
if (typeof options === 'function') {
|
|
callback = options
|
|
options = {}
|
|
}
|
|
|
|
callback = callback || function () {}
|
|
|
|
const url = maToUrl(ma)
|
|
log('dialing %s', url)
|
|
const socket = connect(url, {
|
|
binary: true,
|
|
onConnect: (err) => callback(err)
|
|
})
|
|
|
|
const conn = new Connection(socket)
|
|
conn.getObservedAddrs = (callback) => callback(null, [ma])
|
|
conn.close = (callback) => socket.close(callback)
|
|
|
|
return conn
|
|
}
|
|
|
|
createListener (options, handler) {
|
|
if (typeof options === 'function') {
|
|
handler = options
|
|
options = {}
|
|
}
|
|
|
|
return createListener(options, handler)
|
|
}
|
|
|
|
filter (multiaddrs) {
|
|
if (!Array.isArray(multiaddrs)) {
|
|
multiaddrs = [multiaddrs]
|
|
}
|
|
|
|
return multiaddrs.filter((ma) => {
|
|
if (includes(ma.protoNames(), 'ipfs')) {
|
|
ma = ma.decapsulate('ipfs')
|
|
}
|
|
return mafmt.WebSockets.matches(ma) || mafmt.WebSocketsSecure.matches(ma)
|
|
})
|
|
}
|
|
}
|
|
|
|
module.exports = WebSockets
|