How to use ws method in wpt

Best JavaScript code snippet using wpt

exchange.js

Source:exchange.js Github

copy

Full Screen

1const BFX = require('bitfinex-api-node')2var minimist = require('minimist')3 , path = require('path')4 , n = require('numbro')5module.exports = function bitfinex (conf) {6 var s = {options: minimist(process.argv)}7 var so = s.options8 var ws_connecting = false9 var ws_connected = false10 var ws_timeout = 6000011 var ws_retry = 1000012 var pair, public_client, ws_client13 var ws_trades = []14 var ws_balance = []15 var ws_orders = []16 var ws_ticker = []17 var ws_hb = []18 var ws_walletCalcDone19 var heartbeat_interval20 function publicClient () {21 if (!public_client) public_client = new BFX(null,null, {version: 2, transform: true}).rest22 return public_client23 }24 function wsUpdateTrades (pair, trades) {25 if (trades[0] === 'tu') {26 trades = [trades[1]]27 } else if (trades[0] === 'te') {28 return29 }30 trades.forEach(function (trade) {31 var newTrade = {32 trade_id: Number(trade.ID),33 time: Number(trade.MTS),34 size: Math.abs(trade.AMOUNT),35 price: Number(trade.PRICE),36 side: trade.AMOUNT > 0 ? 'buy' : 'sell'37 }38 ws_trades.push(newTrade)39 })40 if (ws_trades.length > 1010)41 ws_trades.shift()42 }43 function wsUpdateTicker (pair, ticker) {44 ws_ticker = ticker45 }46 function wsMessage (message) {47 if (message.event == 'auth' && message.status == 'OK') {48 if (so.debug) { console.log(('\nWebSockets: We are now fully connected and authenticated.').green) }49 ws_connecting = false50 ws_connected = true51 }52 if (message[0] != 'undefined')53 ws_hb[message[0]] = Date.now()54 }55 function wsUpdateOrder (ws_order) {56 var cid = ws_order[2]57 // https://bitfinex.readme.io/v2/reference#ws-auth-orders58 var order = ws_orders['~' + cid]59 if (!order) {60 if (so.debug) console.warn(('\nWarning: Order ' + cid + ' not found in cache for wsUpdateOrder (manual order?).').red)61 return62 }63 if (ws_order[13] === 'ACTIVE' || ws_order[13].match(/^PARTIALLY FILLED/)) {64 order.status = 'open'65 } else if (ws_order[13].match(/^EXECUTED/)) {66 order.status = 'done'67 } else if (ws_order[13] === 'CANCELED') {68 order.status = 'rejected'69 } else if (ws_order[13] === 'POSTONLY CANCELED') {70 order.status = 'rejected'71 order.reject_reason = 'post only'72 }73 order.bitfinex_id = ws_order[0]74 order.created_at = ws_order[4]75 order.filled_size = n(ws_order[7]).subtract(ws_order[6]).format('0.00000000')76 order.bitfinex_status = ws_order[13]77 order.price = ws_order[16]78 order.price_avg = ws_order[17]79 ws_orders['~' + cid] = order80 }81 function wsUpdateOrderCancel (ws_order) {82 var cid = ws_order[2]83 if (!ws_orders['~' + cid]) {84 if (so.debug) console.warn(('\nWarning: Order ' + cid + ' not found in cache for wsUpdateOrderCancel (manual order?).').red)85 return86 }87 if (ws_order[13].match(/^INSUFFICIENT MARGIN/)) {88 ws_orders['~' + cid].status = 'rejected'89 ws_orders['~' + cid].reject_reason = 'balance'90 }91 setTimeout(function () {92 delete(ws_orders['~' + cid])93 }, 60000 * 60 * 12)94 wsUpdateOrder(ws_order)95 }96 function wsUpdateReqOrder (error) {97 if (error[6] === 'ERROR' && error[7].match(/^Invalid order: not enough .* balance for/)) {98 var cid = error[4][2]99 if (!ws_orders['~' + cid]) {100 if (so.debug) console.warn(('\nWarning: Order ' + cid + ' not found in cache for wsUpdateReqOrder (manual order?).').red)101 return102 }103 ws_orders['~' + cid].status = 'rejected'104 ws_orders['~' + cid].reject_reason = 'balance'105 }106 if (error[6] === 'ERROR' && error[7] === 'Invalid price.') {107 cid = error[4][2]108 if (!ws_orders['~' + cid]) {109 if (so.debug) console.warn(('\nWarning: Order ' + cid + ' not found in cache for wsUpdateReqOrder (manual order?).').red)110 return111 }112 if (so.debug) console.log(ws_orders['~' + cid])113 ws_orders['~' + cid].status = 'rejected'114 ws_orders['~' + cid].reject_reason = 'price'115 }116 }117 function updateWallet(wallets) {118 if (typeof(wallets[0]) !== 'object') wallets = [wallets]119 wallets.forEach(function (wallet) {120 if (wallet[0] === conf.bitfinex.wallet) {121 ws_balance[wallet[1].toUpperCase()] = {}122 ws_balance[wallet[1].toUpperCase()].balance = wallet[2]123 ws_balance[wallet[1].toUpperCase()].available = wallet[4] ? wallet[4] : 0124 ws_balance[wallet[1].toUpperCase()].wallet = wallet[0]125 if (wallet[4] !== null) {126 ws_walletCalcDone[wallet[1]] = true127 }128 }129 })130 }131 function wsConnect () {132 if (ws_connected || ws_connecting) return133 ws_client.open()134 }135 function wsOpen () {136 ws_client.auth()137 ws_client.subscribeTrades(pair)138 ws_client.subscribeTicker(pair)139 }140 function wsSubscribed (event) {141 // We only use the 'trades' channel for heartbeats. That one should be most frequently updated.142 if (event.channel === 'trades') {143 ws_hb[event.chanId] = Date.now()144 heartbeat_interval = setInterval(function() {145 if (ws_hb[event.chanId]) {146 var timeoutThreshold = (Number(Date.now()) - ws_timeout)147 if (timeoutThreshold > ws_hb[event.chanId]) {148 console.warn(('\nWebSockets Warning: No message on channel \'trade\' within ' + ws_timeout / 1000 + ' seconds, reconnecting...').red)149 ws_client.close()150 }151 }152 }, ws_timeout)153 }154 }155 function wsClose () {156 ws_connecting = false157 ws_connected = false158 clearInterval(heartbeat_interval)159 console.error(('\nWebSockets Error: Connection closed.').red + ' Retrying every ' + (ws_retry / 1000 + ' seconds').yellow + '.')160 }161 function wsError (e) {162 console.warn(e)163 ws_connecting = false164 ws_connected = false165 if (e.event == 'auth' && e.status == 'FAILED') {166 var errorMessage = ('\nWebSockets Warning: Authentication ' + e.status + ' (Reason: "' + e.msg + '").').red167 if (e.msg == 'apikey: invalid') errorMessage = errorMessage + '\nEither your API key is invalid or you tried reconnecting to quickly. Wait and/or check your API keys.'168 console.warn(errorMessage)169 ws_client.close()170 }171 else {172 ws_client.close()173 }174 }175 function wsClient () {176 if (!ws_client) {177 if (!conf.bitfinex || !conf.bitfinex.key || conf.bitfinex.key === 'YOUR-API-KEY') {178 throw new Error('please configure your Bitfinex credentials in ' + path.resolve(__dirname, 'conf.js'))179 }180 ws_connecting = true181 ws_connected = false182 ws_client = new BFX(conf.bitfinex.key, conf.bitfinex.secret, {version: 2, transform: true}).ws183 ws_client184 .on('open', wsOpen)185 .on('close', wsClose)186 .on('error', wsError)187 .on('subscribed', wsSubscribed)188 .on('message', wsMessage)189 .on('trade', wsUpdateTrades)190 .on('ticker', wsUpdateTicker)191 .on('ws', updateWallet)192 .on('wu', updateWallet)193 .on('on', wsUpdateOrder)194 .on('on-req', wsUpdateReqOrder)195 .on('ou', wsUpdateOrder)196 .on('oc', wsUpdateOrderCancel)197 .on('miu', marginSymbolWebsocket)198 .on('ps', assetPositionMargin)199 // we need also more position updates here, but messages are completely undocumented200 // https://bitfinex.readme.io/v1/reference#ws-auth-position-updates201 // <pn|pu|pc> possible only "pu" for update202 setInterval(function() {203 wsConnect()204 }, ws_retry)205 }206 }207 /**208 *209 * @param position ['tXRPUSD']210 * @returns {string}211 */212 function assetPositionMarginAssetExtract(position) {213 let pair = position[0]214 // tXRPUSD215 if (pair.substring(0, 1) === 't') {216 pair = pair.substring(1)217 }218 return pair.substring(0, pair.length - 3)219 }220 /**221 * We have no wallet on margin orders; fake current asset capital via open position222 *223 * @param positions224 * @see https://bitfinex.readme.io/v1/reference#ws-auth-position-snapshot225 */226 function assetPositionMargin(positions) {227 // skip non margin228 if(conf.bitfinex.wallet !== 'margin') {229 return230 }231 // current positions in request232 // we need it for clear233 let assets = []234 positions.filter(function (position) {235 return position.length > 2236 }).forEach(function (position) {237 let asset = assetPositionMarginAssetExtract(position)238 if (!ws_balance[asset]) {239 ws_balance[asset] = {}240 }241 assets.push(asset)242 let action = position[1].toLowerCase()243 if(action === 'active') {244 ws_balance[asset].balance = position[2]245 ws_balance[asset].available = position[2]246 ws_balance[asset].wallet = 'margin'247 } else if(action === 'closed') {248 ws_balance[asset].balance = 0249 ws_balance[asset].available = 0250 ws_balance[asset].wallet = 'margin'251 }252 })253 // clear non open positions; which are not existing anymore254 for(let key in ws_balance) {255 if(assets.indexOf(key) < 0 && ws_balance[key]) {256 ws_balance[key].balance = 0257 ws_balance[key].available = 0258 if(so.debug) {259 console.log('Clear asset: ' + JSON.stringify(ws_balance[key]))260 }261 }262 }263 }264 function joinProduct (product_id) {265 return product_id.split('-')[0] + '' + product_id.split('-')[1]266 }267 function retry (method, args, cb) {268 setTimeout(function () {269 exchange[method].call(exchange, args, cb)270 }, ws_retry)271 }272 function waitForCalc (method, args, cb) {273 setTimeout(function () {274 exchange[method].call(exchange, args, cb)275 }, 50)276 }277 function encodeQueryData(data) {278 let ret = []279 for (let d in data)280 ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]))281 return ret.join('&')282 }283 function marginSymbolWebsocket(symbol) {284 /*285 [ 'sym',286 'tBTCUSD',287 [ 101.11144665, // "all" - "active positions"288 179.11144665, // "all"289 78.11144665, // "all" - "active positions" - "active unfilled orders"290 78.11144665, // "all" - "active positions" - "active unfilled orders" ?291 null,292 null,293 null,294 null295 ]296 */297 if(symbol[0] !== 'sym') {298 return299 }300 // tBTCUSD301 if(symbol[1].substring(0, 1) !== 't') {302 return303 }304 let pair = symbol[1].substring(1)305 // not nice but values are not splitted306 // "tBTCUSD" extract => "USD"307 // "tDASHUSD" extract => "USD"308 let currency = symbol[1].substring(symbol[1].length - 3)309 // which array index to use to get available balance? :)310 ws_balance[currency].available = symbol[2][0]311 ws_balance[currency].balance = symbol[2][0]312 ws_walletCalcDone[pair] = true313 }314 function updateBalance(opts) {315 switch (conf.bitfinex.wallet) {316 case 'margin':317 try {318 ws_walletCalcDone[opts.asset] = 'inProgress'319 ws_walletCalcDone[opts.currency] = 'inProgress'320 ws_client.send([0, 'calc', null, [321 ['margin_base'],322 ['margin_sym_' + opts.asset.toUpperCase() + opts.currency.toUpperCase()],323 ['funding_sym_' + opts.currency.toUpperCase()],324 ]])325 } catch (e) {326 if (so.debug) {327 console.warn(e)328 console.warn(('\nWebSockets Warning: Cannot send \'calc\' for getBalance update (maybe connection not open?).').red + ' Waiting for reconnect.')329 }330 }331 break332 case 'exchange':333 try {334 ws_walletCalcDone[opts.asset] = 'inProgress'335 ws_walletCalcDone[opts.currency] = 'inProgress'336 ws_client.send([0, 'calc', null, [337 ['wallet_exchange_' + opts.currency],338 ['wallet_exchange_' + opts.wallet + '_' + opts.asset]339 ]])340 } catch (e) {341 if (so.debug) {342 console.warn(e)343 console.warn(('\nWebSockets Warning: Cannot send \'calc\' for getBalance update (maybe connection not open?).').red + ' Waiting for reconnect.')344 }345 }346 break347 default:348 console.log('not supported wallet:' + opts.wallet)349 }350 }351 var exchange = {352 name: 'bitfinex',353 historyScan: 'backward',354 historyScanUsesTime: true,355 makerFee: 0.1,356 takerFee: 0.2,357 getProducts: function () {358 return require('./products.json')359 },360 getName: function () {361 return this.name;362 },363 getTrades: function (opts, cb) {364 if (!pair) { pair = joinProduct(opts.product_id) }365 // Backfilling using the REST API366 if (opts.to || opts.to === null) {367 var client = publicClient()368 var args = {}369 args.sort = -1 //backward370 args.limit = 1000371 if (opts.from) {372 args.start = opts.from373 }374 else if (opts.to) {375 args.end = opts.to376 }377 else if (args.start && !args.end) {378 args.end = args.start + 500000379 }380 else if (args.end && !args.start) {381 args.start = args.end - 500000382 }383 var query = encodeQueryData(args)384 var tpair = 't' + joinProduct(opts.product_id)385 client.makePublicRequest('trades/' + tpair + '/hist?' + query, function (err, body) {386 if (err) return retry('getTrades', opts, cb)387 var trades = body.map(function(trade) {388 return {389 trade_id: trade.ID,390 time: trade.MTS,391 size: Math.abs(trade.AMOUNT),392 price: trade.PRICE,393 side: trade.AMOUNT > 0 ? 'buy' : 'sell'394 }395 })396 cb(null, trades)397 })398 } else {399 // We're live now (i.e. opts.from is set), use websockets400 if (!ws_client) { wsClient() }401 if (typeof(ws_trades) === 'undefined') { return retry('getTrades', opts, cb) }402 var trades = ws_trades.filter(function (trade) { return trade.time >= opts.from })403 cb(null, trades)404 }405 },406 getBalance: function (opts, cb) {407 if (!pair) {408 pair = joinProduct(opts.asset + '-' + opts.currency)409 }410 if (pair && !ws_walletCalcDone) {411 ws_walletCalcDone = {}412 ws_walletCalcDone[opts.asset] = false413 ws_walletCalcDone[opts.currency] = false414 }415 if (!ws_client) {416 wsClient()417 }418 if (Object.keys(ws_balance).length === 0) {419 if (so.debug && ws_connected === true) {420 console.warn(('WebSockets Warning: Waiting for initial websockets snapshot.').red + ' Retrying in ' + (ws_retry / 1000 + ' seconds').yellow + '.')421 }422 return retry('getBalance', opts, cb)423 }424 if (ws_walletCalcDone[opts.asset] === false && ws_walletCalcDone[opts.currency] === false) {425 updateBalance(opts)426 return waitForCalc('getBalance', opts, cb)427 } else if (428 (ws_walletCalcDone[opts.asset] === false && ws_walletCalcDone[opts.currency] === true) ||429 (ws_walletCalcDone[opts.asset] === true && ws_walletCalcDone[opts.currency] === false)430 ) {431 return waitForCalc('getBalance', opts, cb)432 } else {433 let balance = {}434 balance.currency = ws_balance[opts.currency] && ws_balance[opts.currency].balance ? n(ws_balance[opts.currency].balance).format('0.00000000') : n(0).format('0.00000000')435 balance.asset = ws_balance[opts.asset] && ws_balance[opts.asset].balance ? n(ws_balance[opts.asset].balance).format('0.00000000') : n(0).format('0.00000000')436 balance.currency_hold = ws_balance[opts.currency] && ws_balance[opts.currency].available ? n(ws_balance[opts.currency].balance).subtract(ws_balance[opts.currency].available).format('0.00000000') : n(0).format('0.00000000')437 balance.asset_hold = ws_balance[opts.asset] && ws_balance[opts.asset].available ? n(ws_balance[opts.asset].balance).subtract(ws_balance[opts.asset].available).format('0.00000000') : n(0).format('0.00000000')438 ws_walletCalcDone[opts.asset] = false439 ws_walletCalcDone[opts.currency] = false440 cb(null, balance)441 }442 },443 getQuote: function (opts, cb) {444 cb(null, { bid : String(ws_ticker.BID), ask : String(ws_ticker.ASK) })445 },446 cancelOrder: function (opts, cb) {447 var order = ws_orders['~' + opts.order_id]448 ws_orders['~' + opts.order_id].reject_reason = 'zenbot cancel'449 var ws_cancel_order = [450 0,451 'oc',452 null,453 {454 id: order.bitfinex_id455 }456 ]457 try {458 ws_client.send(ws_cancel_order)459 }460 catch (e) {461 if (so.debug) {462 console.warn(e)463 console.warn(('\nWebSockets Warning: Cannot send cancelOrder (maybe connection not open?).').red + ' Retrying in ' + (ws_retry / 1000 + ' seconds').yellow + '.')464 }465 return retry('cancelOrder', opts, cb)466 }467 cb()468 },469 trade: function (action, opts, cb) {470 if (!pair) { pair = joinProduct(opts.product_id) }471 var symbol = 't' + pair472 if (!ws_client) { wsClient() }473 var cid = Math.round(((new Date()).getTime()).toString() * Math.random())474 var amount = action === 'buy' ? opts.size : opts.size * -1475 var price = opts.price476 // only exchange need a prefix; no needed for margin477 let walletName = conf.bitfinex.wallet.toUpperCase() === 'EXCHANGE' ? 'EXCHANGE ' : ''478 if (opts.order_type === 'maker' && typeof opts.type === 'undefined') {479 opts.type = walletName + 'LIMIT'480 } else if (opts.order_type === 'taker' && typeof opts.type === 'undefined') {481 opts.type = walletName + 'MARKET'482 }483 if (typeof opts.post_only === 'undefined') {484 opts.post_only = true485 }486 var type = opts.type487 var is_postonly = opts.post_only488 var order = {489 id: cid,490 bitfinex_id: null,491 status: 'open',492 price: opts.price,493 size: opts.size,494 post_only: !!opts.post_only,495 created_at: new Date().getTime(),496 filled_size: 0,497 ordertype: opts.order_type498 }499 var ws_order = [500 0,501 'on',502 null,503 {504 cid: cid,505 type: type,506 symbol: symbol,507 amount: String(amount),508 price: price,509 hidden: 0,510 postonly: is_postonly ? 1 : 0511 }512 ]513 try {514 ws_client.send(ws_order)515 }516 catch (e) {517 if (so.debug) {518 console.warn(e)519 console.warn(('\nWebSockets Warning: Cannot send trade (maybe connection not open?).').red + (' Orders are sensitive, we\'re marking this one as rejected and will not just repeat the order automatically.').yellow)520 }521 order.status = 'rejected'522 order.reject_reason = 'could not send order over websockets'523 }524 ws_orders['~' + cid] = order525 return cb(null, order)526 },527 buy: function (opts, cb) {528 exchange.trade('buy', opts, cb)529 },530 sell: function (opts, cb) {531 exchange.trade('sell', opts, cb)532 },533 getOrder: function (opts, cb) {534 var order = ws_orders['~' + opts.order_id]535 if(!order) {536 return cb(new Error('order id ' + opts.order_id + ' not found'))537 }538 if (order.status === 'rejected' && order.reject_reason === 'post only') {539 return cb(null, order)540 } else if (order.status === 'rejected' && order.reject_reason === 'zenbot canceled') {541 return cb(null, order)542 }543 if (order.status == 'done') {544 order.done_at = new Date().getTime()545 return cb(null, order)546 }547 cb(null, order)548 },549 // return the property used for range querying.550 getCursor: function (trade) {551 return (trade.time || trade)552 }553 }554 return exchange...

Full Screen

Full Screen

WikipediaStore.js

Source:WikipediaStore.js Github

copy

Full Screen

1dojo.provide("dojox.data.tests.stores.WikipediaStore");2dojo.require("dojox.data.WikipediaStore");3dojo.require("dojo.data.api.Read");4dojo.require("dojo.data.api.Identity");5dojox.data.tests.stores.WikipediaStore.getStore = function(){6 return new dojox.data.WikipediaStore();7};8dojox.data.tests.stores.WikipediaStore.error = function(t, d, errData){9 // summary:10 // Our shared error callback11 d.errback(errData);12};13doh.register("dojox.data.tests.stores.WikipediaStore",[14 {15 name: "ReadAPI: containsValue",16 timeout: 30000,17 runTest: function(t) {18 // summary:19 // Verify the containsValue method functions correctly.20 var ws = dojox.data.tests.stores.WikipediaStore.getStore();21 var d = new doh.Deferred();22 // hopefully Wikipedia doesn't rename the Main Page!23 ws.fetch({24 query: { title: "Main Page" },25 onComplete: function(items, length){26 t.is(1, items.length);27 t.t(ws.containsValue(items[0], "title", "Main Page"));28 d.callback(true);29 },30 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)31 });32 return d;33 }34 },35 {36 name: "ReadAPI: fetch (one)",37 timeout: 30000,38 runTest: function(t) {39 // summary:40 // Test a single page fetch from Wikipedia41 var ws = dojox.data.tests.stores.WikipediaStore.getStore();42 var d = new doh.Deferred();43 ws.fetch({44 query: { title: "Main Page" },45 onItem: function(item, request){46 t.t(item.title && item.title.length && item.title.length > 0);47 d.callback(true);48 },49 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, doh, d)50 });51 return d;52 }53 },54 {55 name: "ReadAPI: fetch (query 30)",56 timeout: 30000,57 runTest: function(t) {58 // summary:59 // Test a full text search from Wikipedia60 var ws = dojox.data.tests.stores.WikipediaStore.getStore();61 var d = new doh.Deferred();62 ws.fetch({63 query: { action: "query", text: "dojo" },64 count: 30,65 onComplete: function(items, request){66 t.is(30, items.length);67 d.callback(true);68 },69 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)70 });71 return d;72 }73 },74 {75 name: "ReadAPI: fetch (paged)",76 timeout: 30000,77 runTest: function(t) {78 // summary:79 // Test multiple fetches on a single full text search.80 var ws = dojox.data.tests.stores.WikipediaStore.getStore();81 var d = new doh.Deferred();82 var count = 0;83 ws.fetch({84 query: { action: "query", text: "dojo" },85 count: 15,86 onComplete: function(items, request){87 t.is(15, items.length);88 count = items.length;89 ws.fetch({90 query: { action: "query", text: "dojo" },91 start: count+1,92 count: 15,93 onComplete: function(items, request){94 t.is(30, count + items.length);95 d.callback(true);96 }97 });98 },99 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)100 });101 return d;102 }103 },104 {105 name: "ReadAPI: getAttributes",106 timeout: 30000,107 runTest: function(t) {108 // summary:109 // Verify the getAttributes method functions correctly110 var ws = dojox.data.tests.stores.WikipediaStore.getStore();111 var d = new doh.Deferred();112 ws.fetch({113 query: { title: "Main Page" },114 onComplete: function(items, request){115 t.is(1, items.length);116 t.t(ws.isItem(items[0]));117 t.t(ws.getAttributes(items[0]).length > 0);118 d.callback(true);119 },120 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)121 });122 return d;123 }124 },125 {126 name: "ReadAPI: getLabel",127 timeout: 30000,128 runTest: function(t) {129 // summary:130 // Test that the store correctly sets a label.131 var ws = dojox.data.tests.stores.WikipediaStore.getStore();132 var d = new doh.Deferred();133 ws.fetch({134 query: { action: "query", text: "dojo" },135 count: 1,136 onComplete: function(items, request){137 t.is(1, items.length);138 t.t(ws.getLabel(items[0]) !== null);139 d.callback(true);140 },141 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)142 });143 return d;144 }145 },146 {147 name: "ReadAPI: getLabelAttributes",148 timeout: 30000,149 runTest: function(t) {150 // summary:151 // Test that the store correctly enumerates the label attributes.152 var ws = dojox.data.tests.stores.WikipediaStore.getStore();153 var d = new doh.Deferred();154 ws.fetch({155 query: { action: "query", text: "dojo" },156 count: 1,157 onComplete: function(items, request){158 t.is(1, items.length);159 var labels = ws.getLabelAttributes(items[0]);160 t.t(dojo.isArray(labels));161 t.is("title", labels[0]);162 d.callback(true);163 },164 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)165 });166 return d;167 }168 },169 {170 name: "ReadAPI: getValue",171 timeout: 30000,172 runTest: function(t) {173 // summary:174 // Verify that getValue does what it should.175 var ws = dojox.data.tests.stores.WikipediaStore.getStore();176 var d = new doh.Deferred();177 ws.fetch({178 query: { title: "Main Page" },179 onComplete: function(items, request){180 t.is(1, items.length);181 var i = items[0];182 t.t(ws.getValue(i, "text") !== null);183 t.t(ws.getValue(i, "links") !== null);184 t.t(ws.getValue(i, "categories") !== null);185 t.t(ws.getValue(i, "images") !== null);186 d.callback(true);187 },188 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)189 });190 return d;191 }192 },193 {194 name: "ReadAPI: getValues",195 timeout: 30000,196 runTest: function(t) {197 // summary:198 // Verify that getValues does what it should199 var ws = dojox.data.tests.stores.WikipediaStore.getStore();200 var d = new doh.Deferred();201 ws.fetch({202 query: { title: "Main Page" },203 onComplete: function(items, request){204 t.is(1, items.length);205 var i = items[0];206 t.t(dojo.isArray(ws.getValues(i, "text")));207 t.t(dojo.isArray(ws.getValues(i, "links")));208 t.t(dojo.isArray(ws.getValues(i, "categories")));209 t.t(dojo.isArray(ws.getValues(i, "images")));210 d.callback(true);211 },212 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)213 });214 return d;215 }216 },217 {218 name: "ReadAPI: hasAttribute",219 timeout: 30000,220 runTest: function(t) {221 // summary:222 // Verify the hasAttribute method223 var ws = dojox.data.tests.stores.WikipediaStore.getStore();224 var d = new doh.Deferred();225 ws.fetch({226 query: { title: "Main Page" },227 onComplete: function(items, request){228 t.is(1, items.length);229 var i = items[0];230 t.t(i !== null);231 t.t(ws.hasAttribute(i, "title"));232 t.t(ws.hasAttribute(i, "text"));233 t.t(ws.hasAttribute(i, "links"));234 t.t(ws.hasAttribute(i, "categories"));235 t.t(ws.hasAttribute(i, "images"));236 d.callback(true);237 },238 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)239 });240 return d;241 }242 },243 {244 name: "ReadAPI: isItem",245 timeout: 30000,246 runTest: function(t) {247 // summary:248 // Verify the isItem method249 var ws = dojox.data.tests.stores.WikipediaStore.getStore();250 var d = new doh.Deferred();251 ws.fetch({252 query: { action: "query", text: "dojo" },253 count: 10,254 onComplete: function(items, request){255 t.is(10, items.length);256 for(var i=0; i<items.length; i++){257 t.t(ws.isItem(items[i]));258 }259 d.callback(true);260 },261 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)262 });263 return d;264 }265 },266 {267 name: "ReadAPI: isItemLoaded",268 timeout: 30000,269 runTest: function(t) {270 // summary:271 // Verify the isItemLoaded method272 var ws = dojox.data.tests.stores.WikipediaStore.getStore();273 var d = new doh.Deferred();274 ws.fetch({275 query: { action: "query", text: "dojo" },276 count: 5,277 onComplete: function(items, request){278 t.is(5, items.length);279 ws.loadItem({280 item: items[0],281 onItem: function(loadedItem, loadedRequest){282 t.t(ws.isItemLoaded(loadedItem));283 t.f(ws.isItemLoaded(items[1])); // test an invalid item284 d.callback(true);285 }286 });287 },288 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)289 });290 return d;291 }292 },293 {294 name: "IdentityAPI: getIdentity",295 timeout: 30000,296 runTest: function(t) {297 // summary:298 // Verify the getIdentity method returns the correct value299 var ws = dojox.data.tests.stores.WikipediaStore.getStore();300 var d = new doh.Deferred();301 ws.fetch({302 query: { title: "Main Page" },303 onComplete: function(items, request){304 t.is(1, items.length);305 t.t(ws.isItem(items[0]));306 t.t(ws.getIdentity(items[0]) === "Main Page");307 d.callback(true);308 },309 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)310 });311 return d;312 }313 },314 {315 name: "ReadAPI: loadItem",316 timeout: 30000,317 runTest: function(t) {318 // summary:319 // Verify the loadItem method320 var ws = dojox.data.tests.stores.WikipediaStore.getStore();321 var d = new doh.Deferred();322 ws.fetch({323 query: { action: "query", text: "dojo" },324 count: 5,325 onComplete: function(items, request){326 t.is(5, items.length);327 t.t(ws.isItem(items[0]));328 t.t(ws.getIdentityAttributes(items[0]).length > 0);329 ws.loadItem({330 item: items[0],331 onItem: function(item, request){332 t.t(ws.isItem(item));333 t.t(ws.isItemLoaded(item));334 d.callback(true);335 }336 });337 },338 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)339 });340 return d;341 }342 },343 {344 name: "IdentityAPI: getIdentityAttributes",345 timeout: 30000,346 runTest: function(t) {347 // summary:348 // Verify the getIdentityAttributes method functions correctly349 var ws = dojox.data.tests.stores.WikipediaStore.getStore();350 var d = new doh.Deferred();351 ws.fetch({352 query: { title: "Main Page" },353 onComplete: function(items, request){354 t.is(1, items.length);355 t.t(ws.isItem(items[0]));356 t.t(ws.getIdentityAttributes(items[0]).length > 0);357 d.callback(true);358 },359 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)360 });361 return d;362 }363 },364 {365 name: "IdentityAPI: fetchItemByIdentity",366 timeout: 30000,367 runTest: function(t) {368 // summary:369 // Verify the fetchItemByIdentity method works370 var ws = dojox.data.tests.stores.WikipediaStore.getStore();371 var d = new doh.Deferred();372 ws.fetch({373 query: { title: "Main Page" },374 onComplete: function(items, request){375 var firstItem = items[0];376 t.is(1, items.length);377 t.t(ws.isItem(firstItem));378 ws.fetchItemByIdentity({379 identity: "Main Page",380 onItem: function(item, request){381 t.t(ws.isItem(item));382 t.t(ws.getValue(firstItem, "title") === ws.getValue(item, "title"));383 d.callback(true);384 }385 });386 },387 onError: dojo.partial(dojox.data.tests.stores.WikipediaStore.error, t, d)388 });389 return d;390 }391 },392 393 function testIdentityAPI_getFeatures(t){394 // summary:395 // Test that the store correctly advertises its capabilities396 var ws = dojox.data.tests.stores.WikipediaStore.getStore();397 var features = ws.getFeatures();398 var count = 0;399 for(var i in features){400 if(i === "dojo.data.api.Read") count++;401 if(i === "dojo.data.api.Identity") count++;402 }403 t.assertTrue(count === 2);404 },405 function testIdentityAPI_functionConformance(t){406 // summary:407 // Tests for Identity API conformance by checking to see that all declared functions are actual functions on the instances.408 var ws = dojox.data.tests.stores.WikipediaStore.getStore();409 var identityApi = new dojo.data.api.Identity();410 var passed = true;411 for(var i in identityApi){412 if(i.toString().charAt(0) === '_'){413 continue;414 }415 // check that every function defined in the Identity API is defined on the store416 if(typeof identityApi[i] === "function"){417 if(!(typeof ws[i] === "function")){418 console.log("Error:" + i + " should be a function but is: " + typeof ws[i]);419 passed = false;420 break;421 }422 }423 }424 t.assertTrue(passed);425 }...

Full Screen

Full Screen

Internal.js

Source:Internal.js Github

copy

Full Screen

1"use strict";2const WebSocket = require('ws');3exports.createWebsocketImpl = addr => proto => opts => () => {4 return new WebSocket(addr, proto, opts)5}6exports.readyStateImpl = websocket => () => {7 let readyState = (state) => ({8 0: "Connecting",9 1: "Open",10 2: "Closing",11 3: "Closed"12 })[state]13 return { tag: readyState(websocket.readyState) }14}15exports.sendImpl = ws => data => () => {16 ws.send(data)17}18exports.sendImpl_ = ws => data => options => action => () => {19 ws.send(data, options, action)20}21exports.pingImpl = ws => data => mask => action => () => {22 ws.ping(data, mask, action)23}24exports.pongImpl = ws => data => mask => action => () => {25 ws.pong(data, mask, action)26}27exports.closeImpl = (ws) => code => reason => () => { 28 ws.close(code, reason)29}30exports.closeImpl_ = (ws) => () => ws.close()31exports.onopenImpl = ws => cb => () => {32 ws.onopen = cb33}34exports.oncloseImpl = ws => cb => () => {35 ws.onclose = cb36}37exports.onmessageImpl = ws => cb => () => { 38 ws.onmessage = (e) => {39 cb(e.data)()40 }41}42exports.onpingImpl = ws => cb => () => {43 ws.on('ping', (data) => cb(data)())44}45exports.onpongImpl = ws => cb => () => {46 ws.on('pong', (data) => cb(data)())47}48exports.onerrorImpl = ws => cb => () => {49 ws.on('error', (err) => { 50 cb(err)()51 })52}53exports.terminateImpl = ws => () => ws.terminate()54exports.protocolImpl = ws => ws.protocol55exports.urlImpl = ws => ws.url56exports.extensions = ws => ws.extensions...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import { createSlice } from '@reduxjs/toolkit'2export * as selectors from './selector'3const PATH = "APP";4const slice = createSlice({5 name: PATH,6 initialState: {7 wsId: null,8 wsConnected: false,9 wsLoading: false,10 wsError: false,11 },12 reducers: {13 wsConnect: (state) => {14 state.wsId = null15 state.wsConnected = false16 state.wsLoading = true17 state.wsError = null18 },19 wsDisconnect: (state) => {20 state.wsId = null21 state.wsConnected = false22 state.wsLoading = false23 state.wsError = null24 },25 wsOnOpen: (state, action) => {26 state.wsId = action.payload27 state.wsConnected = true28 state.wsLoading = false29 state.wsError = null30 },31 wsOnClose: (state) => {32 state.wsId = null33 state.wsConnected = false34 state.wsLoading = false35 state.wsError = null36 },37 wsOnError: (state, action) => {38 state.wsId = null39 state.wsConnected = false40 state.wsLoading = false41 state.wsError = action.payload42 },43 },44 extraReducers: {45 }46});47export const actions = {48 ...slice.actions,49}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2wptools.page('Barack Obama').get(function(err, page) {3 console.log(page.infobox());4});5var wptools = require('wptools');6wptools.page('Barack Obama').get(function(err, page) {7 console.log(page.json());8});9var wptools = require('wptools');10wptools.page('Barack Obama').get(function(err, page) {11 console.log(page.wikitext());12});13var wptools = require('wptools');14wptools.page('Barack Obama').get(function(err, page) {15 console.log(page.html());16});17var wptools = require('wptools');18wptools.page('Barack Obama').get(function(err, page) {19 console.log(page.html('#mw-content-text'));20});21var wptools = require('wptools');22wptools.page('Barack Obama').get(function(err, page) {23 console.log(page.html('#mw-content-text', '#toc'));24});25var wptools = require('wptools');26wptools.page('Barack Obama').get(function(err, page) {27 console.log(page.html('#mw-content-text', '#toc', true));28});29var wptools = require('wptools');30wptools.page('Barack Obama').get(function(err, page) {31 console.log(page.links());32});33var wptools = require('wptools');34wptools.page('Barack Obama').get(function(err, page) {35 console.log(page.links('external'));36});37var wptools = require('wptools');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var fs = require('fs');3var page = wptools.page('Albert_Einstein');4page.get(function(err, resp) {5 fs.writeFile('test.json', JSON.stringify(resp, null, 2), function(err) {6 if (err) {7 console.log('Error writing file: ' + err);8 }9 else {10 console.log('It\'s saved!');11 }12 });13});14{15 "extract": "Albert Einstein (/ˈaɪnstaɪn/; German: [ˈalbɛɐ̯t ˈʔaɪnʃtaɪn] ( listen); 14 March 1879 – 18 April 1955) was a German-born theoretical physicist. He developed the theory of relativity, one of the two pillars of modern physics (alongside quantum mechanics). Einstein's work is also known for its influence on the philosophy of science. Einstein is best known in popular culture for his mass–energy equivalence formula E = mc2 (which has been dubbed \"the world's most famous equation\"). He received the 1921 Nobel Prize in Physics \"for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect\", a pivotal step in the evolution of quantum theory.",16 "description": "German-born theoretical physicist (1879-1955)",17 {18 }19 {20 },21 {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptool = require('wptool');2ws.get(function(err, res, body){3 console.log(body);4});5### get(callback)6### post(callback)7### put(callback)8### delete(callback)9### head(callback)10### request(method, callback)11### setUrl(url)12### setHeader(name, value)13### setHeaders(headers)14### setBody(body)15### setQuery(query)16### setMethod(method)17### setAuth(user, pass)18### setProxy(proxy)19### setCert(cert)20### setKey(key)21### setCa(ca)22### setPfx(pfx)23### setStrictSSL(strictSSL)24### setAgent(agent)25### setTimeout(timeout)26### setFollowRedirect(followRedirect)27### setMaxRedirects(maxRedirects)28### setEncoding(encoding)29### setGzip(gzip)30### setFormData(formData)31### setMultipart(multipart)32### setJson(json)33### setOauth(oauth)34### setPool(pool)35### setForever(forever)

Full Screen

Using AI Code Generation

copy

Full Screen

1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.9a7d1e4a4c7b0f0e4b7a8b4e1b7a4e4a');3var options = {4};5 if (err) return console.error(err);6 console.log('Test Results: %j', data);7});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var webPageTest = new wpt(options);5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});

Full Screen

Using AI Code Generation

copy

Full Screen

1var WPT = require('wpt-api');2var wpt = new WPT('A.9c88b7e8f1f2d7a4b1c4b7f2d2c4a7a9');3var options = {4};5wpt.runTest(url, options, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});12var WPT = require('wpt-api');13var wpt = new WPT('A.9c88b7e8f1f2d7a4b1c4b7f2d2c4a7a9');14var options = {15};16wpt.runTest(url, options)17 .then(function(data) {18 console.log(data);19 })20 .catch(function(err) {21 console.log(err);22 });23### new WPT(apiKey, [options])24### wpt.runTest(url, [

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful