How to use WS method in redwood

Best JavaScript code snippet using redwood

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

1import { useMutation, useFlash } from '@redwoodjs/web'2import { navigate, routes } from '@redwoodjs/router'3 mutation CreatePostMutation($input: CreatePostInput!) {4 createPost(input: $input) {5 }6 }7const NewPost = () => {8 const { addMessage } = useFlash()9 const [createPost, { loading, error }] = useMutation(CREATE_POST_MUTATION, {10 onCompleted: () => {11 navigate(routes.posts())12 addMessage('Post created.', { classes: 'rw-flash-success' })13 },14 })15 const onSave = (input) => {16 createPost({ variables: { input } })17 }18 return (19 <PostForm onSave={onSave} loading={loading} error={error} />20}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useQuery } from '@redwoodjs/web'2import { useAuth } from '@redwoodjs/auth'3import { Link, routes } from '@redwoodjs/router'4 query {5 posts {6 }7 }8const HomePage = () => {9 const { loading, error, data } = useQuery(QUERY)10 const { logIn, logOut, isAuthenticated, currentUser } = useAuth()11 if (loading) {12 }13 if (error) {14 return <div>Error: {error.message}</div>15 }16 return (17 {data.posts.map((post) => (18 <li key={post.id}>19 <Link to={routes.post({ id: post.id })}>{post.title}</Link>20 ))}21}22import { useMutation } from '@redwoodjs/web'23import { useAuth } from '@redwoodjs/auth'24import { Link, routes } from '@redwoodjs/router'25 mutation CreatePostMutation($input: CreatePostInput!) {26 createPost(input: $input) {27 }28 }29const HomePage = () => {30 const [createPost, { loading, error }] = useMutation(CREATE_POST, {31 onCompleted: () => {32 navigate(routes.posts())33 toast.success('Post created')34 },35 })36 const onSave = (input) => {37 createPost({ variables: { input } })38 }39 return (40 <PostForm onSave={onSave} loading={loading} error={error} />41}42import { useFlash } from '@

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2var ws = redwood.ws;3var redwood = require('redwood');4var http = redwood.http;5var redwood = require('redwood');6var mqtt = redwood.mqtt;7var redwood = require('redwood');8var amqp = redwood.amqp;9var redwood = require('redwood');10var mqtt = redwood.mqtt;11var redwood = require('redwood');12var amqp = redwood.amqp;13var redwood = require('redwood');14var coap = redwood.coap;15var redwood = require('redwood');16var mqtt = redwood.mqtt;17var redwood = require('redwood');18var amqp = redwood.amqp;19var redwood = require('redwood');20var coap = redwood.coap;21var redwood = require('redwood');22var mqtt = redwood.mqtt;23var redwood = require('redwood');24var amqp = redwood.amqp;25var redwood = require('redwood');26var coap = redwood.coap;27var redwood = require('redwood');28var mqtt = redwood.mqtt;29var redwood = require('redwood');30var amqp = redwood.amqp;31var redwood = require('redwood');32var coap = redwood.coap;33var redwood = require('redwood');34var mqtt = redwood.mqtt;35var redwood = require('redwood');36var amqp = redwood.amqp;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { db } = require('@redwoodjs/api')2const { gql } = require('apollo-server-lambda')3const { ApolloServer } = require('apollo-server-lambda')4 type Query {5 }6const resolvers = {7 Query: {8 hello: () => 'Hello world!',9 },10}11const schema = makeExecutableSchema({12})13const handler = createGraphQLHandler({14})15const { ApolloServer } = require('apollo-server-lambda')16const { typeDefs, resolvers } = require('../graphql')17const apolloServer = new ApolloServer({18})19exports.handler = apolloServer.createHandler({20 cors: {21 },22})23const { gql } = require('apollo-server-lambda')24 type Query {25 }26const resolvers = {27 Query: {28 hello: () => 'Hello world!',29 },30}31module.exports = {32}

Full Screen

Using AI Code Generation

copy

Full Screen

1var ws = require('redwood/ws');2var ws = require('redwood/ws.js');3var ws = require('redwood/ws/index.js');4var ws = require('redwood/ws');5var ws = require('redwood/ws.js');6var ws = require('redwood/ws/index.js');7var ws = require('redwood/ws');8var ws = require('redwood/ws.js');9var ws = require('redwood/ws/index.js');10var ws = require('redwood/ws');11var ws = require('redwood/ws.js');12var ws = require('redwood/ws/index.js');

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2 if (err) {3 console.log(err);4 } else {5 console.log(body);6 }7});8var redwood = require('redwood');9 if (err) {10 console.log(err);11 } else {12 console.log(body);13 }14});15var redwood = require('redwood');16 if (err) {17 console.log(err);18 } else {19 console.log(body);20 }21});22var redwood = require('redwood');23 if (err) {24 console.log(err);25 } else {26 console.log(body);27 }28});29var redwood = require('redwood');30 if (err) {31 console.log(err);32 } else {33 console.log(body);34 }35});36var redwood = require('redwood');37 if (err) {38 console.log(err);39 } else {40 console.log(body);41 }42});43var redwood = require('redwood');44 if (err) {45 console.log(err);46 } else {47 console.log(body);48 }49});50var redwood = require('redwood');51 if (err) {52 console.log(err);53 } else {

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2var client = redwood.createClient();3client.connect('localhost', 1234, function() {4 client.call('add', [1, 2], function(err, result) {5 console.log(result);6 });7});8var redwood = require('redwood');9var client = redwood.createClient();10client.connect('localhost', 1234, function() {11 client.call('add', [1, 2], function(err, result) {12 console.log(result);13 });14});15### redwood.createServer([options,] [callback])16### server.on('connection', function(client) {})17### server.on('close', function() {})18### server.close()19### client.on('close', function() {})20### client.close()21### client.on('error', function(err) {})22### client.call(method, [params], callback)23### client.call(method, [params])24### client.call(method, [params], callback)25### client.call(method, [params])

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2redwood.init('test', 'test');3redwood.ws('test', 'test', 'test', 'test', 'test', function(err, res) {4 console.log(res);5});6var redwood = require('redwood');7redwood.init('test', 'test');8redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {9 console.log(res);10});11var redwood = require('redwood');12redwood.init('test', 'test');13redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {14 console.log(res);15});16var redwood = require('redwood');17redwood.init('test', 'test');18redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {19 console.log(res);20});21var redwood = require('redwood');22redwood.init('test', 'test');23redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {24 console.log(res);25});26var redwood = require('redwood');27redwood.init('test', 'test');28redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {29 console.log(res);30});31var redwood = require('redwood');32redwood.init('test', 'test');33redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {34 console.log(res);35});36var redwood = require('redwood');37redwood.init('test', 'test');38redwood.http('test', 'test', 'test', 'test', 'test', function(err, res) {39 console.log(res);40});

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2var redwoodWS = new redwood.WebService({version: 1.1, debug: true, pretty: true});3redwoodWS.call('get', 'account', {id: 1}, function(err, data){4 console.log(data);5});6var redwood = require('redwood');7var redwoodHTTP = new redwood.HttpClient({version: 1.1, debug: true, pretty: true});8redwoodHTTP.call('get', 'account', {id: 1}, function(err, data){9 console.log(data);10});11var redwood = require('redwood');12var redwoodJSONP = new redwood.JsonpClient({version: 1.1, debug: true, pretty: true});13redwoodJSONP.call('get', 'account', {id: 1}, function(err, data){14 console.log(data);15});16var redwood = require('redwood');17var redwoodJSONP = new redwood.JsonpClient({version: 1.1, debug: true, pretty: true});18redwoodJSONP.call('get', 'account', {id: 1}, function(err, data){19 console.log(data);20});21var redwood = require('redwood');22var redwoodJSONP = new redwood.JsonpClient({version: 1.1, debug: true, pretty: true});23redwoodJSONP.call('get', 'account', {id: 1}, function(err, data){24 console.log(data);25});26var redwood = require('redwood');27var redwoodJSONP = new redwood.JsonpClient({version: 1.1, debug: true, pretty: true});28redwoodJSONP.call('get', 'account', {id: 1}, function(err, data){29 console.log(data);30});31var redwood = require('redwood');

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 redwood 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