1
0
mirror of https://github.com/fluencelabs/js-libp2p-websockets synced 2025-04-08 20:08:16 +00:00

61 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-03-23 16:23:10 +01:00
'use strict'
2016-08-11 14:50:44 +02:00
const connect = require('pull-ws/client')
2016-03-14 21:19:42 +00:00
const mafmt = require('mafmt')
const includes = require('lodash.includes')
const Connection = require('interface-connection').Connection
2017-03-23 15:09:06 +00:00
const maToUrl = require('./ma-to-url')
2016-08-11 14:50:44 +02:00
const debug = require('debug')
const log = debug('libp2p:websockets:dialer')
2016-08-11 14:50:44 +02:00
const createListener = require('./listener')
2016-03-14 20:25:00 +00:00
2017-03-23 15:09:06 +00:00
class WebSockets {
2016-08-11 14:50:44 +02:00
dial (ma, options, callback) {
if (typeof options === 'function') {
callback = options
2016-03-14 20:25:00 +00:00
options = {}
}
2017-03-23 15:09:06 +00:00
callback = callback || function () {}
2017-03-23 15:09:06 +00:00
const url = maToUrl(ma)
2016-08-11 14:50:44 +02:00
log('dialing %s', url)
const socket = connect(url, {
binary: true,
onConnect: (err) => callback(err)
})
2016-08-11 14:50:44 +02:00
const conn = new Connection(socket)
2017-03-23 15:09:06 +00:00
conn.getObservedAddrs = (callback) => callback(null, [ma])
conn.close = (callback) => socket.close(callback)
2016-03-14 20:25:00 +00:00
return conn
}
2016-08-11 14:50:44 +02:00
createListener (options, handler) {
2016-03-14 20:25:00 +00:00
if (typeof options === 'function') {
handler = options
options = {}
}
2016-08-11 14:50:44 +02:00
return createListener(options, handler)
2016-03-14 20:25:00 +00:00
}
2016-08-11 14:50:44 +02:00
filter (multiaddrs) {
if (!Array.isArray(multiaddrs)) {
multiaddrs = [multiaddrs]
}
2016-08-11 14:50:44 +02:00
2016-03-14 20:25:00 +00:00
return multiaddrs.filter((ma) => {
if (includes(ma.protoNames(), 'ipfs')) {
ma = ma.decapsulate('ipfs')
}
2017-03-23 15:09:06 +00:00
return mafmt.WebSockets.matches(ma) || mafmt.WebSocketsSecure.matches(ma)
2016-03-14 20:25:00 +00:00
})
}
}
2017-03-23 15:09:06 +00:00
module.exports = WebSockets