code stringlengths 28 313k | docstring stringlengths 25 85.3k | func_name stringlengths 1 74 | language stringclasses 1
value | repo stringlengths 5 60 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
healthCheck = async function(checkId) {
if (process.env.NODE_ENV !== "production") return;
try {
let resp = null;
const source = CancelToken.source();
setTimeout(() => {
if (resp === null) source.cancel("ECONNTIMEOUT");
}, 10000);
resp = await AxiosService.create().get(
urljoin("http... | Ping healthchecks.io
@param {string} checkId | healthCheck | javascript | openupm/openupm | app/utils/healthCheck.js | https://github.com/openupm/openupm/blob/master/app/utils/healthCheck.js | BSD-3-Clause |
httpErrorInfo = function(err, others) {
// Show http status if possible or fallback to error
if (err.response && err.response.status)
return { status: err.response.status, ...others };
else return { err, ...others };
} | Return HTTP error info object
@param {Object} error
@param {Object} others | httpErrorInfo | javascript | openupm/openupm | app/utils/http.js | https://github.com/openupm/openupm/blob/master/app/utils/http.js | BSD-3-Clause |
isErrorCode = function(error, code) {
return error.response && error.response.status == code;
} | Return if error has given status code.
@param {Object} error
@param {Number} code | isErrorCode | javascript | openupm/openupm | app/utils/http.js | https://github.com/openupm/openupm/blob/master/app/utils/http.js | BSD-3-Clause |
addImage = async function({
imageUrl,
width,
height,
fit,
duration,
filename,
force
}) {
const key = getMediaKey({ imageUrl, width, height, fit });
const expire = new Date().getTime() + duration;
const oldImageEntry = await getImage({ imageUrl, width, height, fit });
// download image to a tmp fi... | Download, process a image and upload to S3.
@param {object} param0 | addImage | javascript | openupm/openupm | app/utils/media.js | https://github.com/openupm/openupm/blob/master/app/utils/media.js | BSD-3-Clause |
_downloadImageUrl = async function(imageUrl, destPath) {
let resp = null;
const source = CancelToken.source();
setTimeout(() => {
if (resp === null) source.cancel("ECONNTIMEOUT");
}, 10000);
const headers = {};
resp = await AxiosService.create().get(imageUrl, {
headers,
cancelToken: source.token... | Download the image url to the dest path
@param {string} imageUrl
@param {string} destPath | _downloadImageUrl | javascript | openupm/openupm | app/utils/media.js | https://github.com/openupm/openupm/blob/master/app/utils/media.js | BSD-3-Clause |
_processImage = async function({
sourcePath,
destLocalPath,
destS3Path,
width,
height,
fit
}) {
const image = sharp(sourcePath);
await image
.resize(width, height, {
fit,
background: { r: 255, g: 255, b: 255, alpha: 0 }
})
.png()
.toFile(destLocalPath);
// copy to s3
awai... | Process the image and upload to s3
@param {object} param0 | _processImage | javascript | openupm/openupm | app/utils/media.js | https://github.com/openupm/openupm/blob/master/app/utils/media.js | BSD-3-Clause |
getMediaS3Path = function(filename) {
return `media/${filename}`;
} | Get media S3 path
@param {string} filename | getMediaS3Path | javascript | openupm/openupm | app/utils/media.js | https://github.com/openupm/openupm/blob/master/app/utils/media.js | BSD-3-Clause |
getMediaTempFilename = function({ imageUrl, width, height, fit }) {
const md5 = crypto
.createHash("md5")
.update(imageUrl)
.digest("hex");
const now = new Date().getTime();
return `${md5}-${width}x${height}-${fit}-${now}.tmp`;
} | Get media tmp filename
@param {object} param0 | getMediaTempFilename | javascript | openupm/openupm | app/utils/media.js | https://github.com/openupm/openupm/blob/master/app/utils/media.js | BSD-3-Clause |
getImage = async function({ imageUrl, width, height, fit }) {
const key = getMediaKey({ imageUrl, width, height, fit });
const obj = await redis.client.hgetall(key);
if (isEmpty(obj))
return null;
obj.size = parseInt(obj.size) || 0;
if (!obj.filename)
obj.filename = getMediaFilename({
imageUrl,
... | Get the image entry { available, filename, filePath, s3Path, expire, size }
@param {object} param0 | getImage | javascript | openupm/openupm | app/utils/media.js | https://github.com/openupm/openupm/blob/master/app/utils/media.js | BSD-3-Clause |
readJsFile = function(file, onComplete, ...callbackArgs) {
fs.readFile(path.relative(process.cwd(), file), 'utf8', function(err, code) {
if (err) {
return console.error(err);
}
onComplete(file, code, ...callbackArgs);
});
} | @todo Add features from the Non-CLI side of this module such as:
2. Custom abstraction level
3. Presentation mode
4. Defined colour schemes (default, B&W, blurred, light)
5. Custom colour scheme
6. Custom style
7. Flow tree modifications (iterative methods treated as loops, ...)
8. Custom modifier
9. Debugging
@todo Co... | readJsFile | javascript | Bogdan-Lyashenko/js-code-to-svg-flowchart | cli/index.cli.js | https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart/blob/master/cli/index.cli.js | MIT |
writeToFile = function(filePath, data) {
fs.writeFile(filePath, data, function(err) {
if (err) {
return console.error(err);
}
console.log(`SVG file was created: ${filePath}`);
});
} | @description Write data to the specified file path.
@param {string} filePath Path of the destination file
@param {*} data Data to write to the destination | writeToFile | javascript | Bogdan-Lyashenko/js-code-to-svg-flowchart | cli/index.cli.js | https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart/blob/master/cli/index.cli.js | MIT |
createAbstractedSvgFile = function(file, code, abstractionLevel) {
const errMsg =
'Please use (case insensitive, without the quotes): "function", "function_dependencies", "class", "import" or "export"';
if (!abstractionLevel) return console.error(`No abstraction level specified`);
const flowTreeBuil... | @description Create an SVG file with the provided abstraction level
@param {string} file Name of the JS script
@param {string} code JS code of the JS script
@param {...string} abstractionLevel Abstraction levels (function, function dependencies, class, import, export)
@return undefined | createAbstractedSvgFile | javascript | Bogdan-Lyashenko/js-code-to-svg-flowchart | cli/index.cli.js | https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart/blob/master/cli/index.cli.js | MIT |
function downloadFromOverpass (
queryName,
overpassConfig,
filename,
overpassDownloadCallback
) {
let query = '[out:json][timeout:60];('
if (overpassConfig.way) {
query += 'way'
} else {
query += 'relation'
}
const queryKeys = Object.keys(overpassConfig)
for (let i = queryKeys.length - 1; ... | Download something from overpass and convert it into GeoJSON.
@param {string} queryName Name of the query (for debugging purposes)
@param {object} overpassConfig Config used to build overpass query
@param {string} filename Filename to save result to
@param {function} overpassDownloadCallback The callback to cal... | downloadFromOverpass | javascript | evansiroky/timezone-boundary-builder | index.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/index.js | MIT |
function getDataSource (source) {
let geoJson
if (source.source === 'overpass') {
geoJson = require(getSourceDownloadName(source.id))
} else if (source.source === 'manual-polygon') {
geoJson = polygon(source.data).geometry
} else if (source.source === 'manual-multipolygon') {
geoJson = multiPolygon(... | Get the geometry of the requested source data
@return {Object} geom The geometry of the source
@param {Object} source An object representing the data source
must have `source` key and then either:
- `id` if from a file
- `id` if from a file | getDataSource | javascript | evansiroky/timezone-boundary-builder | index.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/index.js | MIT |
function postProcessZone (geom, returnAsObject) {
// reduce precision of geometry
const geojson = geomToGeoJson(precisionReducer.reduce(geom))
// iterate through all polygons
const filteredPolygons = []
let allPolygons = geojson.coordinates
if (geojson.type === 'Polygon') {
allPolygons = [geojson.coord... | Post process created timezone boundary.
- remove small holes and exclaves
- reduce geometry precision
@param {Geometry} geom The jsts geometry of the timezone
@param {boolean} returnAsObject if true, return as object, otherwise return stringified
@return {Object|String} geojson as object or stringified | postProcessZone | javascript | evansiroky/timezone-boundary-builder | index.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/index.js | MIT |
beginTask (message, logTimeLeft) {
this.printStats(message, logTimeLeft)
this.logNext()
} | Begin a new task. Print the current progress and then increment the number of tasks.
@param {string} A short message about the current task progress
@param {[boolean]} logTimeLeft whether or not to log the time left. | beginTask | javascript | evansiroky/timezone-boundary-builder | util/progressStats.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/util/progressStats.js | MIT |
printStats (message, logTimeLeft) {
message = `${message}; ${this.trackerName} progress: ${this.getPercentage()}% done`
if (logTimeLeft) {
message = `${message} - ${this.getTimeLeft()} left`
}
console.log(message)
} | Print the current progress.
@param {string} A short message about the current task progress
@param {[boolean]} logTimeLeft whether or not to log the time left. | printStats | javascript | evansiroky/timezone-boundary-builder | util/progressStats.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/util/progressStats.js | MIT |
getPercentage () {
const current = (this.taskCounter / this.totalTasks)
return Math.round(current * 1000.0) / 10.0
} | calculates the percentage of finished downloads
@returns {string} | getPercentage | javascript | evansiroky/timezone-boundary-builder | util/progressStats.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/util/progressStats.js | MIT |
getTimeLeft () {
if (this.taskCounter === 0) return '?'
const averageTimePerTask = (Date.now() - this.beginTime.getTime()) / this.taskCounter
const tasksLeft = this.totalTasks - this.taskCounter
const millisecondsLeft = averageTimePerTask * tasksLeft
return this.formatMilliseconds(millisecondsLeft)
... | calculates the time left and outputs it in human readable format
calculation is based on the average time per task so far
@returns {string} | getTimeLeft | javascript | evansiroky/timezone-boundary-builder | util/progressStats.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/util/progressStats.js | MIT |
formatMilliseconds (millisec) {
const seconds = (millisec / 1000).toFixed(1)
const minutes = (millisec / (1000 * 60)).toFixed(1)
const hours = (millisec / (1000 * 60 * 60)).toFixed(1)
const days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1)
if (seconds < 60) {
return seconds + ' seconds'
... | inspired from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
@param millisec
@returns {string} | formatMilliseconds | javascript | evansiroky/timezone-boundary-builder | util/progressStats.js | https://github.com/evansiroky/timezone-boundary-builder/blob/master/util/progressStats.js | MIT |
ObjectProperty(path) {
if (
DATA_FETCH_FNS.includes(path.node.value.name) &&
path.findParent(
(path) =>
path.isVariableDeclarator() &&
path.node.id.name === 'layoutProps',
)
) {
path.remove()
}
} | Currently it's not possible to export data fetching functions from MDX pages
because MDX includes them in `layoutProps`, and Next.js removes them at some
point, causing a `ReferenceError`.
https://github.com/mdx-js/mdx/issues/742#issuecomment-612652071
This plugin can be removed once MDX removes `layoutProps`, at lea... | ObjectProperty | javascript | jaredpalmer/tsdx | website/.nextra/babel-plugin-nextjs-mdx-patch.js | https://github.com/jaredpalmer/tsdx/blob/master/website/.nextra/babel-plugin-nextjs-mdx-patch.js | MIT |
function _createCanvas(){
var canvasses = document.getElementById("canvasses");
var canvas = document.createElement("canvas");
// Dimensions
var _onResize = function(){
var width = canvasses.clientWidth;
var height = canvasses.clientHeight;
canvas.width = width*2; // retina
canvas.style.width = width+"px"... | **************************
A miscellaneous collection of reuseable helper methods
that I couldn't be arsed to put into separate classes
*************************** | _createCanvas | javascript | ncase/loopy | splash/js/helpers.js | https://github.com/ncase/loopy/blob/master/splash/js/helpers.js | CC0-1.0 |
function Ink(loopy){
var self = this;
self.loopy = loopy;
// Create canvas & context
var canvas = _createCanvas();
var ctx = canvas.getContext("2d");
self.canvas = canvas;
self.context = ctx;
// Stroke data!
self.strokeData = [];
// Drawing!
self.drawInk = function(){
if(!Mouse.pressed) return;
// ... | *******************************
LOOPY!
- with edit & play mode
TODO: smoother bezier curve?
TODO: when switch away tool, clear the Ink canvas
******************************** | Ink | javascript | ncase/loopy | splash/js/Ink.js | https://github.com/ncase/loopy/blob/master/splash/js/Ink.js | CC0-1.0 |
_onUpdate = function(){
var embedCode = '<iframe width="'+width.getValue()+'" height="'+height.getValue()+'" frameborder="0" src="'+iframeSRC+'"></iframe>';
output.output(embedCode);
} | ********************
Use the same PAGE UI thing
********************** | _onUpdate | javascript | ncase/loopy | splash/js/Modal.js | https://github.com/ncase/loopy/blob/master/splash/js/Modal.js | CC0-1.0 |
function PageUI(dom){
var self = this;
self.dom = dom;
self.pages = [];
self.addPage = function(id, page){
page.id = id;
self.dom.appendChild(page.dom);
self.pages.push(page);
};
self.currentPage = null;
self.showPage = function(id){
var shownPage = null;
for(var i=0; i<self.pages.length; i++){
va... | *******************************
PAGE UI: to extend to Sidebar, Play Controls, Modal.
******************************** | PageUI | javascript | ncase/loopy | splash/js/PageUI.js | https://github.com/ncase/loopy/blob/master/splash/js/PageUI.js | CC0-1.0 |
function PlayButton(config){
var self = this;
var label = "<div class='play_button_icon' icon='"+config.icon+"'></div> "
+ "<div class='play_button_label'>"+config.label+"</div>";
self.dom = _createButton(label, function(){
config.onclick();
});
// Tooltip!
if(config.tooltip){
self.dom.setAttribute("d... | *******************************
PLAY CONTROLS CODE:
- play
- pause/reset/speed
******************************** | PlayButton | javascript | ncase/loopy | splash/js/PlayControls.js | https://github.com/ncase/loopy/blob/master/splash/js/PlayControls.js | CC0-1.0 |
constructor (opts = {
apiKey: '',
apiSecret: '',
authToken: '',
company: '',
transform: false,
ws: {},
rest: {}
}) {
if (opts.constructor.name !== 'Object') {
throw new Error([
'constructor takes an object since version 2.0.0, see:',
'https://github.com/bitfinexco... | @param {object} [opts] - options
@param {string} [opts.apiKey] - API key
@param {string} [opts.apiSecret] - API secret
@param {string} [opts.authToken] - optional auth option
@param {string} [opts.company] - optional auth option
@param {boolean} [opts.transform] - if true, packets are converted to models
@param {object... | constructor | javascript | bitfinexcom/bitfinex-api-node | index.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/index.js | MIT |
_getTransportPayload (extraOpts) {
return {
apiKey: this._apiKey,
apiSecret: this._apiSecret,
authToken: this._authToken,
company: this._company,
transform: this._transform,
...extraOpts
}
} | Returns an arguments map ready to pass to a transport constructor
@param {object} extraOpts - options to pass to transport
@returns {object} payload | _getTransportPayload | javascript | bitfinexcom/bitfinex-api-node | index.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/index.js | MIT |
rest (version = 2, extraOpts = {}) {
if (version !== 1 && version !== 2) {
throw new Error(`invalid http API version: ${version}`)
}
const key = `${version}|${JSON.stringify(extraOpts)}`
if (!this._transportCache.rest[key]) {
Object.assign(extraOpts, this._restArgs)
const payload = t... | Returns a new REST API class instance (cached by version)
@param {number} [version] - 1 or 2 (default)
@param {object} [extraOpts] - passed to transport constructor
@returns {RESTv1|RESTv2} transport | rest | javascript | bitfinexcom/bitfinex-api-node | index.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/index.js | MIT |
ws (version = 2, extraOpts = {}) {
if (version !== 1 && version !== 2) {
throw new Error(`invalid websocket API version: ${version}`)
}
const key = `${version}|${JSON.stringify(extraOpts)}`
if (!this._transportCache.ws[key]) {
Object.assign(extraOpts, this._wsArgs)
const payload = th... | Returns a new WebSocket API class instance (cached by version)
@param {number} [version] - 1 or 2 (default)
@param {object} [extraOpts] - passed to transport constructor
@returns {WSv1|WSv2} transport | ws | javascript | bitfinexcom/bitfinex-api-node | index.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/index.js | MIT |
debugTable = ({ rows = [], headers, widths }, extraRows = []) => {
debug('')
debugTableUtil({
rows: [...rows, ...extraRows],
headers,
widths,
debug
})
debug('')
} | Log a table to the console
@param {object} args - arguments
@param {object[]} args.rows - data, can be specified as 2nd param
@param {string[]} args.headers - column labels
@param {number[]} args.widths - column widths
@param {object[]} extraRows - optional row spec as 2nd param | debugTable | javascript | bitfinexcom/bitfinex-api-node | examples/util/setup.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/examples/util/setup.js | MIT |
constructor (socketArgs, authArgs = { calc: 0, dms: 0 }) {
super()
this.setMaxListeners(1000)
this._authArgs = authArgs
this._sockets = []
this._socketArgs = {
...(socketArgs || {}),
reconnectThrottler
}
} | @param {object} socketArgs - passed to WSv2 constructors
@param {object} [authArgs] - cached for all internal socket auth() calls
@param {number} [authArgs.calc] - default 0
@param {number} [authArgs.dms] - default 0 | constructor | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
setAuthArgs (args = {}) {
this._authArgs = {
...this._authArgs,
...args
}
this._sockets.forEach(socket => socket.ws.updateAuthArgs(this._authArgs))
} | Update authentication arguments on all sockets
@param {object} args - arguments
@param {number} [args.calc] - calc value
@param {number} [args.dms] - active 4 | setAuthArgs | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
getAuthArgs () {
return this._authArgs
} | Retrieve internal authentication arguments
@returns {object} args | getAuthArgs | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
async reconnect () {
return Promise.all(this._sockets.map(socket => socket.ws.reconnect()))
} | Reconnects all open sockets
@returns {Promise} p | reconnect | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
async close () {
return Promise.all(this._sockets.map(socket => socket.ws.close()))
} | Closes all open sockets
@returns {Promise} p | close | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
static getDataChannelCount (s) {
let count = s.ws.getDataChannelCount()
count += s.pendingSubscriptions.length
count -= s.pendingUnsubscriptions.length
return count
} | @param {object} s - socket state
@returns {number} count - # of subscribed/pending data channels | getDataChannelCount | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
getSocket (i) {
return this._sockets[i]
} | @param {number} i - index into pool
@returns {object} state | getSocket | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
getSocketInfo () {
return this._sockets.map(s => ({
nChannels: WS2Manager.getDataChannelCount(s)
}))
} | Returns an object which can be logged to inspect the socket pool
@returns {object[]} socketInfo | getSocketInfo | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
auth ({ apiKey, apiSecret, calc, dms } = {}) {
if (this._socketArgs.apiKey || this._socketArgs.apiSecret) {
debug('error: auth credentials already provided! refusing auth')
return
}
this._socketArgs.apiKey = apiKey
this._socketArgs.apiSecret = apiSecret
if (_isFinite(calc)) this._authA... | Authenticates all existing & future sockets with the provided credentials.
Does nothing if an apiKey/apiSecret pair are already known.
@param {object} args - arguments
@param {string} args.apiKey - saved if not already provided
@param {string} args.apiSecret - saved if not already provided
@param {number} [args.calc] ... | auth | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
getSocketWithDataChannel (type, filter) {
return this._sockets.find(s => {
const subI = s.pendingSubscriptions.findIndex(s => (
s[0] === type && _isEqual(s[1], filter)
))
if (subI !== -1) {
return true
}
// Confirm unsub is not pending
const cid = s.ws.getDataCh... | Returns the first socket that is subscribed/pending sub to the specified
channel.
@param {string} type - i.e. 'book'
@param {object} filter - i.e. { symbol: 'tBTCUSD', prec: 'R0' }
@returns {object} wsState - undefined if not found | getSocketWithDataChannel | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
getSocketWithChannel (chanId) {
return this._sockets.find(s => {
return (
s.ws.hasChannel(chanId) &&
!_includes(s.pendingUnsubscriptions, chanId)
)
})
} | NOTE: Cannot filter against pending subscriptions, due to unknown chanId
@param {number} chanId - channel ID
@returns {object} wsState - undefined if not found | getSocketWithChannel | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
getSocketWithSubRef (channel, identifier) {
return this._sockets.find(s => s.ws.hasSubscriptionRef(channel, identifier))
} | @param {string} channel - channel type
@param {string} identifier - unique channel identifier
@returns {object} wsState - undefined if not found | getSocketWithSubRef | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
withAllSockets (cb) {
this._sockets.forEach((ws2) => {
cb(ws2)
})
} | Calls the provided cb with all internal socket instances
@param {Function} cb - callback | withAllSockets | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
subscribe (type, ident, filter) {
let s = this.getFreeDataSocket()
if (!s) {
s = this.openSocket()
}
const doSub = () => {
s.ws.managedSubscribe(type, ident, filter)
}
if (!s.ws.isOpen()) {
s.ws.once('open', doSub)
} else {
doSub()
}
s.pendingSubscriptions.... | Subscribes a free data socket if available to the specified channel, or
opens a new socket & subs if needed.
@param {string} type - i.e. 'book'
@param {string} ident - i.e. 'tBTCUSD'
@param {object} filter - i.e. { symbol: 'tBTCUSD', prec: 'R0' } | subscribe | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
managedUnsubscribe (channel, identifier) {
const s = this.getSocketWithSubRef(channel, identifier)
if (!s) {
debug('cannot unsub from unknown channel %s: %s', channel, identifier)
return
}
const chanId = s.ws._chanIdByIdentifier(channel, identifier)
s.ws.managedUnsubscribe(channel, ide... | @param {string} channel - channel type
@param {string} identifier - unique channel identifier | managedUnsubscribe | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
unsubscribe (chanId) {
const s = this.getSocketWithChannel(chanId)
if (!s) {
debug('cannot unsub from unknown channel: %d', chanId)
return
}
s.ws.unsubscribe(chanId)
s.pendingUnsubscriptions.push(chanId)
} | Unsubscribes the first socket w/ the specified channel. Does nothing if no
such socket is found.
@param {number} chanId - channel ID | unsubscribe | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
subscribeTicker (symbol) {
this.subscribe('ticker', symbol, { symbol })
} | @param {string} symbol - symbol for ticker | subscribeTicker | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
subscribeTrades (symbol) {
this.subscribe('trades', symbol, { symbol })
} | @param {string} symbol - symbol for trades | subscribeTrades | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
subscribeOrderBook (symbol, prec = 'P0', len = '25', freq = 'F0') {
const filter = {}
if (symbol) filter.symbol = symbol
if (prec) filter.prec = prec
if (len) filter.len = len
if (freq) filter.freq = freq
this.subscribe('book', symbol, filter)
} | @param {string} symbol - symbol for order book
@param {string} [prec] - precision, i.e. 'R0', default 'P0'
@param {string} [len] - length, default '25'
@param {string} [freq] - default 'F0' | subscribeOrderBook | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
subscribeCandles (key) {
this.subscribe('candles', key, { key })
} | @param {string} key - candle channel key | subscribeCandles | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
onCandle ({ key, cbGID }, cb) {
const s = this.getSocketWithDataChannel('candles', { key })
if (!s) {
throw new Error('no data socket available; did you provide a key?')
}
s.ws.onCandle({ key, cbGID }, cb)
} | @param {object} opts - options
@param {string} opts.key - candle set key, i.e. trade:30m:tBTCUSD
@param {string} [opts.cbGID] - callback group id
@param {Function} cb - callback
@throws an error if no data socket is available
@see https://docs.bitfinex.com/v2/reference#ws-public-candle | onCandle | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
onOrderBook ({ symbol, prec = 'P0', len = '25', freq = 'F0', cbGID }, cb) {
const filter = {}
if (symbol) filter.symbol = symbol
if (prec) filter.prec = prec
if (len) filter.len = len
if (freq) filter.freq = freq
const s = this.getSocketWithDataChannel('book', filter)
if (!s) {
thro... | @param {object} opts - options
@param {string} opts.symbol - order book symbol
@param {string} [opts.prec] - precision, i.e. 'R0', default 'P0'
@param {string} [opts.len] - length, default '25'
@param {string} [opts.freq] - default 'F0'
@param {string} [opts.cbGID] - callback group id
@param {Function} cb - callback
@t... | onOrderBook | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
onTrades ({ symbol, cbGID }, cb) {
const s = this.getSocketWithDataChannel('trades', { symbol })
if (!s) {
throw new Error('no data socket available; did you provide a symbol?')
}
s.ws.onTrades({ symbol, cbGID }, cb)
} | @param {object} opts - options
@param {string} [opts.symbol] - symbol for trades
@param {string} [opts.cbGID] - callback group id
@param {Function} cb - callback
@throws an error if no data socket is available
@see https://docs.bitfinex.com/v2/reference#ws-public-trades | onTrades | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
onTicker ({ symbol = '', cbGID } = {}, cb) {
const s = this.getSocketWithDataChannel('ticker', { symbol })
if (!s) {
throw new Error('no data socket available; did you provide a symbol?')
}
s.ws.onTicker({ symbol, cbGID }, cb)
} | @param {object} opts - options
@param {string} [opts.symbol] - symbol for ticker
@param {string} [opts.cbGID] - callback group id
@param {Function} cb - callback
@throws an error if no data socket is available
@see https://docs.bitfinex.com/v2/reference#ws-public-ticker | onTicker | javascript | bitfinexcom/bitfinex-api-node | lib/ws2_manager.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js | MIT |
updateAuthArgs (args = {}) {
this._authArgs = {
...this._authArgs,
...args
}
} | Set `calc` and `dms` values to be used on the next {@link WSv2#auth} call
@param {object} args - arguments
@param {number} [args.calc] - calc value
@param {number} [args.dms] - dms value, active 4
@param {number} [args.apiKey] API key
@param {number} [args.apiSecret] API secret
@see WSv2#auth | updateAuthArgs | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
getDataChannelCount () {
return Object
.values(this._channelMap)
.filter(c => _includes(DATA_CHANNEL_TYPES, c.channel))
.length
} | Get the total number of data channels this instance is currently
subscribed too.
@returns {number} count
@see WSv2#subscribeTrades
@see WSv2#subscribeTicker
@see WSv2#subscribeCandles
@see WSv2#subscribeOrderBook | getDataChannelCount | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
hasChannel (chanId) {
return !!this._channelMap[chanId]
} | Check if the instance is subscribed to the specified channel ID
@param {number} chanId - ID of channel to query
@returns {boolean} isSubscribed | hasChannel | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
hasSubscriptionRef (channel, identifier) {
const key = `${channel}:${identifier}`
return !!Object.keys(this._subscriptionRefs).find(ref => ref === key)
} | Check if a channel/identifier pair has been subscribed too
@param {string} channel - channel type
@param {string} identifier - unique identifier for the reference
@returns {boolean} hasRef
@see WSv2#managedSubscribe | hasSubscriptionRef | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
getDataChannelId (type, filter) {
return Object
.keys(this._channelMap)
.find(cid => {
const c = this._channelMap[cid]
const fv = _pick(c, Object.keys(filter))
return c.channel === type && _isEqual(fv, filter)
})
} | Fetch the ID of a channel matched by type and channel data filter
@param {string} type - channel type
@param {object} filter - to be matched against channel data
@returns {number} channelID | getDataChannelId | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
hasDataChannel (type, filter) {
return !!this.getDataChannelId(type, filter)
} | Check if the instance is subscribed to a data channel matching the
specified type and filter.
@param {string} type - channel type
@param {object} filter - to be matched against channel data
@returns {boolean} hasChannel | hasDataChannel | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
async open () {
if (this._isOpen || this._ws !== null) {
throw new Error('already open')
}
debug('connecting to %s...', this._url)
this._ws = new WebSocket(this._url, {
agent: this._agent
})
this._subscriptionRefs = {}
this._candles = {}
this._orderBooks = {}
this._ws... | Opens a connection to the API server. Rejects with an error if a
connection is already open. Resolves on success.
@returns {Promise} p | open | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
async close (code, reason) {
if (!this._isOpen || this._ws === null) {
throw new Error('not open')
}
debug('disconnecting...')
return new Promise((resolve) => {
this._ws.once('close', () => {
this._isOpen = false
this._ws = null
debug('disconnected')
resolv... | Closes the active connection. If there is none, rejects with a promise.
Resolves on success
@param {number} code - passed to ws
@param {string} reason - passed to ws
@returns {Promise} p | close | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
async auth (calc, dms) {
this._authOnReconnect = true
if (!this._isOpen) {
throw new Error('not open')
}
if (this._isAuthenticated) {
throw new Error('already authenticated')
}
const authNonce = nonce()
const authPayload = `AUTH${authNonce}${authNonce}`
const { sig } = genA... | Generates & sends an authentication packet to the server; if already
authenticated, rejects with an error, resolves on success.
If a DMS flag of 4 is provided, all open orders are cancelled when the
connection terminates.
@param {number?} calc - optional, default is 0
@param {number?} dms - optional dead man switch f... | auth | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
async reconnect () {
this._isReconnecting = true
if (this._ws !== null && this._isOpen) { // did we get a watchdog timeout and need to close the connection?
await this.close()
return new Promise((resolve) => {
this.once(this._authOnReconnect ? 'auth' : 'open', resolve)
})
}
... | Utility method to close & re-open the ws connection. Re-authenticates if
previously authenticated
@returns {Promise} p - resolves on completion | reconnect | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_validateMessageSeq (msg = []) {
if (!this._seqAudit) return null
if (!Array.isArray(msg)) return null
if (msg.length === 0) return null
// The auth sequence # is the last value in channel 0 non-heartbeat packets.
const authSeq = msg[0] === 0 && msg[1] !== 'hb'
? msg[msg.length - 1]
: N... | Returns an error if the message has an invalid (out of order) sequence #
The last-seen sequence #s are updated internally.
@param {Array} msg - incoming message
@returns {Error} err - null if no error or sequencing not enabled
@private | _validateMessageSeq | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
async _triggerPacketWD () {
if (!this._packetWDDelay || !this._isOpen) {
return Promise.resolve()
}
debug(
'packet delay watchdog triggered [last packet %dms ago]',
Date.now() - this._packetWDLastTS
)
this._packetWDTimeout = null
return this.reconnect()
} | Trigger the packet watch-dog; called when we haven't seen a new WS packet
for longer than our WD duration (if provided)
@returns {Promise} p
@private | _triggerPacketWD | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_resetPacketWD () {
if (!this._packetWDDelay) return
if (this._packetWDTimeout !== null) {
clearTimeout(this._packetWDTimeout)
}
if (!this._isOpen) return
this._packetWDTimeout = setTimeout(() => {
this._triggerPacketWD().catch((err) => {
debug('error triggering packet watchdog... | Reset the packet watch-dog timeout. Should be called on every new WS packet
if the watch-dog is enabled
@private | _resetPacketWD | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
resubscribePreviousChannels () {
Object.values(this._prevChannelMap).forEach((chan) => {
const { channel } = chan
switch (channel) {
case 'ticker': {
const { symbol } = chan
this.subscribeTicker(symbol)
break
}
case 'trades': {
const { sy... | Subscribes to previously subscribed channels, used after reconnecting
@private | resubscribePreviousChannels | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_onWSNotification (arrN) {
const status = arrN[6]
const msg = arrN[7]
if (!arrN[4]) return
if (arrN[1] === 'on-req') {
const [,, cid] = arrN[4]
const k = `order-new-${cid}`
if (status === 'SUCCESS') {
this._eventCallbacks.trigger(k, null, arrN[4])
} else {
this... | @param {Array} arrN - notification in ws array format
@private | _onWSNotification | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_onWSMessage (rawMsg, flags) {
debug('recv msg: %s', rawMsg)
this._packetWDLastTS = Date.now()
this._resetPacketWD()
let msg
try {
msg = JSON.parse(rawMsg)
} catch (e) {
this.emit('error', `invalid message JSON: ${rawMsg}`)
return
}
debug('recv msg: %j', msg)
i... | @param {string} rawMsg - incoming message JSON
@param {string} flags - flags
@private | _onWSMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleChannelMessage (msg, rawMsg) {
const [chanId, type] = msg
const channelData = this._channelMap[chanId]
if (!channelData) {
debug('recv msg from unknown channel %d: %j', chanId, msg)
return
}
if (msg.length < 2) return
if (msg[1] === 'hb') return
if (channelData.channel ... | @param {Array} msg - message
@param {string} rawMsg - message JSON
@private | _handleChannelMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleOBChecksumMessage (msg, chanData) {
this.emit('cs', msg)
if (!this._manageOrderBooks) {
return
}
const { symbol, prec } = chanData
const cs = msg[2]
// NOTE: Checksums are temporarily disabled for funding books, due to
// invalid book sorting on the backend. This change... | @param {Array} msg - message
@param {object} chanData - channel definition
@private | _handleOBChecksumMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleOBMessage (msg, chanData, rawMsg) {
const { symbol, prec } = chanData
const raw = prec === 'R0'
let data = getMessagePayload(msg)
if (this._manageOrderBooks) {
const err = this._updateManagedOB(symbol, data, raw, rawMsg)
if (err) {
this.emit('error', err)
return
... | Called for messages from the 'book' channel. Might be an update or a
snapshot
@param {Array|Array[]} msg - message
@param {object} chanData - entry from _channelMap
@param {string} rawMsg - message JSON
@private | _handleOBMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_updateManagedOB (symbol, data, raw, rawMsg) {
// parse raw string with lossless parse which takes
// the exact strict values rather than converting to floats
// [0.00001, [1, 2, 3]] -> ['0.00001', ['1', '2', '3']]
const rawLossless = LosslessJSON.parse(rawMsg, (key, value) => {
if (value && value... | @param {string} symbol - symbol for order book
@param {number[]|number[][]} data - incoming data
@param {boolean} raw - if true, the order book is considered R*
@param {string} rawMsg - source message JSON
@returns {Error} err - null on success
@private | _updateManagedOB | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_verifyManagedOBChecksum (symbol, prec, cs) {
const ob = this._losslessOrderBooks[symbol]
if (!ob) return null
const localCS = ob instanceof OrderBook
? ob.checksum()
: OrderBook.checksumArr(ob, prec === 'R0')
return localCS !== cs
? new Error(`OB checksum mismatch: got ${localCS}, ... | @param {string} symbol - symbol for order book
@param {string} prec - precision
@param {number} cs - expected checksum
@returns {Error} err - null if none
@private | _verifyManagedOBChecksum | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
getOB (symbol) {
if (!this._orderBooks[symbol]) return null
return new OrderBook(this._orderBooks[symbol])
} | Returns an up-to-date copy of the order book for the specified symbol, or
null if no OB is managed for that symbol.
Set `managedOrderBooks: true` in the constructor to use.
@param {string} symbol - symbol for order book
@returns {OrderBook} ob - null if not found
@example
const ws = new WSv2({ managedOrderBooks: tr... | getOB | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
getLosslessOB (symbol) {
if (!this._losslessOrderBooks[symbol]) return null
return new OrderBook(this._losslessOrderBooks[symbol])
} | Returns an up-to-date lossless copy of the order book for the specified symbol, or
null if no OB is managed for that symbol. All amounts and prices are in original
string format.
Set `manageOrderBooks: true` in the constructor to use.
@param {string} symbol - symbol for order book
@returns {OrderBook} ob - null if no... | getLosslessOB | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleTradeMessage (msg, chanData) {
const eventName = msg[1][0] === 'f'
? msg[1] // Funding trades are passed to fte/ftu handlers
: msg[1] === 'te'
? 'trade-entry'
: 'trades'
let payload = getMessagePayload(msg)
if (!Array.isArray(payload[0])) {
payload = [payload]
... | @param {Array} msg - incoming message
@param {object} chanData - channel definition
@private | _handleTradeMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleCandleMessage (msg, chanData) {
const { key } = chanData
let data = getMessagePayload(msg)
if (this._manageCandles) {
const err = this._updateManagedCandles(key, data)
if (err) {
this.emit('error', err)
return
}
data = this._candles[key]
} else if (data.... | Called for messages from a 'candles' channel. Might be an update or
snapshot.
@param {Array|Array[]} msg - incoming message
@param {object} chanData - entry from _channelMap
@private | _handleCandleMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleStatusMessage (msg, chanData) {
const { key } = chanData
const data = getMessagePayload(msg)
const internalMessage = [chanData.chanId, 'status', data]
internalMessage.filterOverride = [chanData.key]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('status', ... | Called for messages from a 'status' channel.
@param {Array|Array[]} msg - incoming message
@param {object} chanData - entry from _channelMap
@private | _handleStatusMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_updateManagedCandles (key, data) {
if (Array.isArray(data[0])) { // snapshot, new candles
data.sort((a, b) => b[0] - a[0])
this._candles[key] = data
return null
}
// entry, needs to be applied to candle set
if (!this._candles[key]) {
return new Error(`recv update for unknown c... | @param {string} key - key for candle set
@param {number[]|number[][]} data - incoming dataset (single or multiple)
@returns {Error} err - null on success
@private | _updateManagedCandles | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
getCandles (key) {
return this._candles[key] || []
} | Fetch a reference to the full set of synced candles for the specified key.
Set `managedCandles: true` in the constructor to use.
@param {string} key - key for candle set
@returns {Array} candles - empty array if none exist
@example
const ws = new WSv2({ managedCandles: true })
ws.on('open', async () => {
ws... | getCandles | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleAuthMessage (msg, chanData) {
if (msg[1] === 'n') {
const payload = getMessagePayload(msg)
if (payload) {
this._onWSNotification(payload)
}
} else if (msg[1] === 'te') {
msg[1] = 'auth-te'
} else if (msg[1] === 'tu') {
msg[1] = 'auth-tu'
}
this._propaga... | @param {Array} msg - incoming message
@param {object} chanData - channel data
@private | _handleAuthMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_propagateMessageToListeners (msg, chan, transform = this._transform) {
const listenerGroups = Object.values(this._listeners)
for (let i = 0; i < listenerGroups.length; i++) {
WSv2._notifyListenerGroup(listenerGroups[i], msg, transform, this, chan)
}
} | @param {Array} msg - incoming message
@param {object} chan - channel data
@param {boolean} transform - defaults to internal flag
@private | _propagateMessageToListeners | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
static _notifyListenerGroup (lGroup, msg, transform, ws, chanData) {
const [, eventName, data = []] = msg
let filterByData
// Catch-all can't filter/transform
WSv2._notifyCatchAllListeners(lGroup, msg)
if (!lGroup[eventName] || lGroup[eventName].length === 0) return
const listeners = lGroup[e... | Applies filtering & transform to a packet before sending it out to matching
listeners in the group.
@param {object} lGroup - listener group to parse & notify
@param {object} msg - passed to each matched listener
@param {boolean} transform - whether or not to instantiate a model
@param {WSv2} ws - instance to pass to m... | _notifyListenerGroup | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
static _payloadPassesFilter (payload, filter) {
const filterIndices = Object.keys(filter)
let filterValue
for (let k = 0; k < filterIndices.length; k++) {
filterValue = filter[filterIndices[k]]
if (_isEmpty(filterValue) || filterValue === '*') {
continue
}
if (payload[+fil... | @param {Array} payload - payload to verify
@param {object} filter - filter to match against payload
@returns {boolean} pass
@private | _payloadPassesFilter | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
static _notifyCatchAllListeners (lGroup, data) {
if (!lGroup['']) return
for (let j = 0; j < lGroup[''].length; j++) {
lGroup[''][j].cb(data)
}
} | @param {object} lGroup - listener group keyed by event ('' in this case)
@param {*} data - packet to pass to listeners
@private | _notifyCatchAllListeners | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleEventMessage (msg) {
if (msg.event === 'auth') {
this._handleAuthEvent(msg)
} else if (msg.event === 'subscribed') {
this._handleSubscribedEvent(msg)
} else if (msg.event === 'unsubscribed') {
this._handleUnsubscribedEvent(msg)
} else if (msg.event === 'info') {
this._hand... | @param {object} msg - incoming message
@private | _handleEventMessage | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_handleAuthEvent (data = {}) {
const { chanId, msg = '', status = '' } = data
if (status !== 'OK') {
const err = new Error(msg.match(/nonce/)
? 'auth failed: nonce small; you may need to generate a new API key to reset the nonce counter'
: `auth failed: ${msg} (${status})`
)
... | @param {object} data - incoming message
@private | _handleAuthEvent | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
managedSubscribe (channel = '', identifier = '', payload = {}) {
const key = `${channel}:${identifier}`
if (this._subscriptionRefs[key]) {
this._subscriptionRefs[key]++
return false
}
this._subscriptionRefs[key] = 1
this.subscribe(channel, payload)
return true
} | Subscribes and tracks subscriptions per channel/identifier pair. If
already subscribed to the specified pair, nothing happens.
@param {string} channel - channel name
@param {string} identifier - for uniquely identifying the ref count
@param {object} payload - merged with sub packet
@returns {boolean} subSent
@todo wil... | managedSubscribe | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
managedUnsubscribe (channel = '', identifier = '') {
const key = `${channel}:${identifier}`
const chanId = this._chanIdByIdentifier(channel, identifier)
if (chanId === null || isNaN(this._subscriptionRefs[key])) return false
this._subscriptionRefs[key]--
if (this._subscriptionRefs[key] > 0) return... | Decreases the subscription ref count for the channel/identifier pair, and
unsubscribes from the channel if it reaches 0.
@param {string} channel - channel name
@param {string} identifier - for uniquely identifying the ref count
@returns {boolean} unsubSent | managedUnsubscribe | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
getChannelData ({ chanId, channel, symbol, key }) {
const id = chanId || this._chanIdByIdentifier(channel, symbol || key)
return this._channelMap[id] || null
} | Fetch a channel definition
@param {object} opts - options
@param {number} opts.chanId - channel ID
@param {string} opts.channel - channel name
@param {string} [opts.symbol] - match by symbol
@param {string} [opts.key] - match by key (for candle channels)
@returns {object} chanData - null if not found | getChannelData | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_chanIdByIdentifier (channel, identifier) {
const channelIds = Object.keys(this._channelMap)
let chan
for (let i = 0; i < channelIds.length; i++) {
chan = this._channelMap[channelIds[i]]
if (chan.channel === channel && (
chan.symbol === identifier ||
chan.key === identifier
... | @param {string} channel - channel name
@param {string} identifier - unique identifier for the channel
@returns {number} channelID
@private | _chanIdByIdentifier | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_getEventPromise (key) {
return new Promise((resolve, reject) => {
this._eventCallbacks.push(key, (err, res) => {
if (err) {
return reject(err)
}
resolve(res)
})
})
} | @param {string} key - key for the promise
@returns {Promise} p - resolves on event
@private | _getEventPromise | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
send (msg) {
if (!this._ws || !this._isOpen) {
this.emit('error', new Error('no ws client or not open'))
} else if (this._isClosing) {
this.emit('error', new Error('connection currently closing'))
} else {
debug('sending %j', msg)
this._ws.send(JSON.stringify(msg))
}
} | Send a packet to the WS server
@param {*} msg - packet, gets stringified | send | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
async enableFlag (flag) {
this._enabledFlags = this._enabledFlags | flag
if (!this._isOpen) {
return
}
this.sendEnabledFlags()
return this._getEventPromise(this._getConfigEventKey(flag))
} | Enables a configuration flag.
@param {number} flag - flag to update, as numeric value
@returns {Promise} p
@see WSv2#flags
@example
const ws = new WSv2()
ws.on('open', async () => {
await ws.enableFlag(WSv2.flags.CHECKSUM)
console.log('ob checkums enabled')
})
await ws.open() | enableFlag | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
sendEnabledFlags () {
this.send({
event: 'conf',
flags: this._enabledFlags
})
} | Sends the local flags value to the server, updating the config
@private | sendEnabledFlags | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
isFlagEnabled (flag) {
return (this._enabledFlags & flag) === flag
} | Checks local state, relies on successful server config responses
@see enableFlag
@param {number} flag - flag to check for
@returns {boolean} enabled | isFlagEnabled | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
_getConfigEventKey (flag) {
return `conf-res-${flag}`
} | @param {string} flag - flag to fetch event key for
@returns {string} key
@private | _getConfigEventKey | javascript | bitfinexcom/bitfinex-api-node | lib/transports/ws2.js | https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.