How to use observeWorker method in ava

Best JavaScript code snippet using ava

uploader.js

Source:uploader.js Github

copy

Full Screen

1import { ObserveWorker } from '../utils/observe-worker'2// TODO API get urls3// TODO API stitch4// TODO resume5function emptyFn() { }6function parse(data) {7 let result = data8 try { result = JSON.parse(data) } catch (error) { }9 return result10}11export default function Uploader(options, file) {12 const methods = {}13 const rejectedUpload = (status, error) => {14 methods.cancel = () => { }15 methods.upload = () => Promise.reject({ error, status })16 return methods17 }18 const Options = Object.assign({}, {19 progressCB: emptyFn,20 completeCB: emptyFn,21 errorCB: emptyFn,22 url: location.href,23 bytesPerChunk: 647212,24 withCredentials: false,25 uploadMethod: 'POST',26 headers: {},27 parallel: false28 }, options)29 function getFile() {30 if (file instanceof Blob || file instanceof File) {31 return file32 }33 if (file instanceof FileList) {34 return file[0]35 }36 }37 function getTotal(file, bytesPerChunk) {38 return !!bytesPerChunk && bytesPerChunk > 0 ? Math.ceil(file.size / bytesPerChunk) : 139 }40 const uploadMessages = []41 const completedChunks = []42 const fileObject = getFile()43 const size = fileObject ? fileObject.size : 044 const total = fileObject ? getTotal(fileObject, Options.bytesPerChunk) : 045 const uploadData = Object.assign({},46 Options,47 { size: size, total: total, fileObject: fileObject }48 )49 /** TEMP */50 // uploadData.total = 551 // uploadData.size = uploadData.total * uploadData.bytesPerChunk52 // uploadData.fileObject = 'hey'53 // uploadData.url = 'hey'54 /** END TEMP */55 let stop = false56 let chunkIndex = 057 Object.defineProperty(methods, 'currentChunk', {58 get: function () {59 return chunkIndex60 }61 })62 Object.defineProperty(methods, 'data', {63 get: function () {64 return uploadData65 }66 })67 if (!uploadData.fileObject || !uploadData.size || !uploadData.total) {68 uploadData.errorCB('invalid file')69 return rejectedUpload(-1, 'Invalid file')70 }71 if (!uploadData.url) {72 uploadData.errorCB('Invalid upload url')73 return rejectedUpload(-1, 'Invalid upload url')74 }75 const worker$ = ObserveWorker(function workerFunction() {76 self.onmessage = function (e) {77 let data = e.data78 try {79 data = JSON.parse(e.data)80 } catch (error) { }81 const x = new XMLHttpRequest()82 x.open(data.method, data.url, true)83 x.withCredentials = data.withCredentials84 function headersEach(key) {85 return x.setRequestHeader(key, data.headers[key])86 }87 Object.keys(data.headers).forEach(headersEach)88 x.onloadend = function () {89 let response = ''90 try {91 response = JSON.stringify({92 response: x.response,93 statusText: x.statusText,94 status: x.status95 })96 } catch (error) { }97 self.postMessage(response)98 }99 x.send(data.data)100 }101 })102 function setProgress() {103 const currentProgress = uploadData.total == 1 ?104 1 :105 !completedChunks.length ?106 0 :107 Math.ceil((completedChunks.length / uploadData.total) * 100) / 100108 return uploadData.progressCB(currentProgress <= 1 ? currentProgress : 1)109 }110 function getHeaders(index, chunkSize, fileSize) {111 return Object.assign({}, {112 'Content-Type': 'application/octet-stream',113 'X-Chunk-Id': index,114 'X-Chunk-Length': chunkSize,115 'X-File-Length': fileSize116 }, uploadData.headers)117 }118 function uploadUrl(index, url) {119 return !Array.isArray(url) ? url : url[index]120 }121 function getChunk(index) {122 return uploadData.total == 1 ?123 uploadData.fileObject :124 uploadData.fileObject.slice(index * uploadData.bytesPerChunk, (index + 1) * uploadData.bytesPerChunk)125 }126 function populateData(index) {127 const data = getChunk(index)128 return {129 data: data,130 url: uploadUrl(index, uploadData.url),131 method: uploadData.uploadMethod,132 withCredentials: uploadData.withCredentials,133 headers: getHeaders(index, data.size, uploadData.fileObject.size),134 }135 }136 function onChunkUploaded(e) {137 if (!e) { return Promise.reject({ status: 500, error: 'An error occured during upload, please try again' }) }138 const data = parse(e)139 if (data.status !== 200) { return Promise.reject({ status: data.status, error: 'An error occured during upload, please try again' }) }140 completedChunks.push(chunkIndex)141 uploadMessages.push({ chunk: chunkIndex, data: data })142 // increment current chunk index143 chunkIndex = chunkIndex + 1144 // update progress145 setProgress()146 // if more chunks to upload147 if (chunkIndex < uploadData.total) {148 return uploadChunk(chunkIndex)149 } else {150 worker$.dispose()151 return Promise.resolve()152 }153 }154 function onChunkUploadedAsync(index, e) {155 if (!e) { return Promise.reject({ status: 500, error: 'An error occured during upload, please try again' }) }156 const data = parse(e)157 if (data.status !== 200) { return Promise.reject({ status: data.status, error: 'An error occured during upload, please try again' }) }158 completedChunks.push(index)159 uploadMessages.push({ chunk: index, data: data })160 setProgress()161 return Promise.resolve()162 }163 function uploadChunk(index) {164 return new Promise(165 function uploadChunkPromise(resolve, reject) {166 if (stop) { return reject({ status: 1000, error: 'Upload was canceled' }) }167 const toSend = populateData(index)168 return worker$.post(toSend)169 .then(onChunkUploaded)170 .then(resolve)171 .catch(reject)172 }173 )174 }175 function uploadChunkAsync(index) {176 return new Promise(177 function uploadChunkAsyncPromise(resolve, reject) {178 if (stop) { return reject({ status: 1000, error: 'Upload was canceled' }) }179 const toSend = populateData(index)180 return worker$.post(toSend)181 .then(function populateDataResult(res) {182 return onChunkUploadedAsync(index, res)183 })184 .then(resolve)185 .catch(reject)186 }187 )188 }189 function upload() {190 if (stop) {191 worker$.dispose()192 uploadData.errorCB('Upload was canceled')193 return Promise.reject({ status: 1000, error: 'Upload was canceled' })194 }195 uploadData.progressCB(0)196 if (!uploadData.parallel) {197 return uploadChunk(chunkIndex)198 .then(res => uploadData.completeCB(res))199 .catch(res => uploadData.errorCB(res))200 }201 const chunkArray = []202 let index = 0203 while (index < uploadData.total) {204 chunkArray.push(index)205 index = index + 1206 }207 return Promise.all(chunkArray.map(c => uploadChunkAsync(c)))208 .then(uploadMessages => uploadData.completeCB(uploadMessages))209 .catch(res => uploadData.errorCB(res))210 }211 methods.cancel = () => stop = true212 methods.upload = upload213 // function fakeUpload(totalModifier) {214 // return new Promise((resolve, reject) => {215 // uploadData.progressCB(0)216 // let i = 0217 // const run = () => {218 // if (stop) {219 // uploadData.errorCB('Upload was canceled')220 // return reject({ status: 1000, error: 'Upload was canceled' })221 // }222 // if (i == (uploadData.total + (totalModifier || 0))) {223 // uploadData.completeCB('fakeUpload done')224 // return resolve('fakeUpload done')225 // }226 // i = i + 1227 // uploadData.progressCB(Math.round((i / uploadData.total) * 100))228 // setTimeout(run, 1234)229 // }230 // run()231 // })232 // }233 // methods.upload = fakeUpload234 // function fakeUploadThenError() {235 // return new Promise((_resolve, reject) => {236 // return fakeUpload(-2)237 // .then(() => { throw new Error() })238 // .catch(() => reject({ status: 500, error: 'Oops, aww shucks' }))239 // })240 // }241 // methods.upload = fakeUploadThenError242 return methods...

Full Screen

Full Screen

request.js

Source:request.js Github

copy

Full Screen

1import { ObserveWorker } from '../utils/observe-worker.js'2import { ObjectAssign } from '../utils/object-assign.js'3export function Request(apiBase) {4 return function (reqData) {5 reqData = reqData ? reqData : {}6 const base = apiBase7 const path = ''.concat(base, ''.concat('/', reqData.path || '').split('//').join('/'))8 const REQ = ObjectAssign(9 {},10 {11 data: undefined,12 headers: {},13 method: 'POST'14 },15 reqData,16 { path: path }17 )18 const isFormData = REQ.data instanceof FormData19 if (!isFormData && REQ.data && typeof REQ.data !== 'string') {20 REQ.data = JSON.stringify(REQ.data)21 }22 if (isFormData) {23 REQ.toForm = true24 const jsonData = {}25 REQ.data.forEach(function (value, key) {26 jsonData[key] = value27 })28 REQ.data = JSON.stringify(REQ.data)29 }30 return new Promise(31 function RequestPromise(resolve, reject) {32 let workerSubscription33 const worker$ = ObserveWorker(34 function () {35 self.onmessage = function (e) {36 var xhr = new XMLHttpRequest()37 var data = JSON.parse(e.data)38 var formData = data.data39 var form = new FormData()40 function formDataKeysEach(key) {41 return form.append(key, formData[key])42 }43 function onloadFn() {44 postMessage({ status: xhr.status, response: xhr.responseText || xhr.statusText })45 }46 function onerrorFn() {47 postMessage({ status: xhr.status, response: xhr.statusText })48 }49 function headersEach(key) {50 xhr.setRequestHeader(key, data.headers[key])51 }52 if (data.toForm) {53 Object.keys(formData).forEach(formDataKeysEach)54 formData = form55 }56 xhr.open(data.method, data.path, false)57 Object.keys(data.headers).forEach(headersEach)58 xhr.onload = onloadFn59 xhr.onerror = onerrorFn60 xhr.send(data.data)61 }62 }63 )64 function workerSub(e) {65 workerSubscription()66 let res = e.response67 try { res = JSON.parse(res) } catch (error) { }68 if (e.status === 200) {69 return resolve(res)70 } else {71 return reject(e)72 }73 }74 function workerError(e) {75 workerSubscription()76 reject(e)77 }78 workerSubscription = worker$.subscribe(workerSub, workerError)79 worker$.post(REQ)80 }81 )82 }...

Full Screen

Full Screen

observe.js

Source:observe.js Github

copy

Full Screen

1"use strict";23const BaseWorker = require('./base');45class ObserveWorker extends BaseWorker {6 constructor(){ super('observe', { quota: true, critical: 'observe', ignoreRoads: true }); }78 /// Job ///910 genTarget(cluster, subtype, id, args){11 if(id.indexOf('-') > 0){12 let parts = id.split('-');13 let pos = { pos: new RoomPosition(parseInt(parts[1]), parseInt(parts[2]), parts[0]), range: 15 };14 return _.get(Game.rooms, [parts[0], 'controller'], pos);15 }else{16 return Game.getObjectById(id);17 }18 }1920 createId(cluster, subtype, target, args){21 return target.pos.roomName + '-25-25';22 }2324 observe(cluster, subtype){25 let unobservedRooms = _.pick(Memory.observe || {}, timeout => timeout > Game.time);26 const targets = _.reduce(Memory.rooms, (result, data, name)=>{27 if(data.cluster == cluster.id && data.observe){28 let targetRoom = Game.rooms[name];29 if(targetRoom && targetRoom.controller && targetRoom.controller.my){30 delete Memory.rooms[name].observe;31 }32 let target;33 if(!targetRoom || !targetRoom.controller){34 target = { pos: new RoomPosition(25, 25, name), range: 15 };35 }else{36 target = targetRoom.controller;37 }38 if(!targetRoom && !unobservedRooms[name]){39 unobservedRooms[name] = Game.time + 200;40 }41 result.push(target);42 }43 return result;44 }, []);45 Memory.observe = unobservedRooms;46 return this.jobsForTargets(cluster, subtype, targets);47 }4849 /// Creep ///5051 continueJob(cluster, creep, opts, job){52 if(opts.onlyReveal && Game.rooms[job.target.pos.roomName]){53 return false;54 }55 return super.continueJob(cluster, creep, opts, job) && (!opts.onlyReveal || !job.target.id);56 }5758 calculateBid(cluster, creep, opts, job, distance){59 if(opts.onlyReveal && Game.rooms[job.target.pos.roomName]){60 return false;61 }62 return distance / 50;63 }6465 process(cluster, creep, opts, job, target){66 if(creep.pos.getRangeTo(target) > (target.range || 3)){67 this.move(creep, target);68 }69 }7071}72 ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1navigator.serviceWorker.addEventListener('message', function(e) {2 console.log(e.data);3});4navigator.serviceWorker.controller.postMessage('Hello from the page!');5navigator.serviceWorker.addEventListener('message', function(e) {6 console.log(e.data);7});8navigator.serviceWorker.controller.postMessage('Hello from the page!');9navigator.serviceWorker.addEventListener('message', function(e) {10 console.log(e.data);11});12navigator.serviceWorker.controller.postMessage('Hello from the page!');13navigator.serviceWorker.addEventListener('message', function(e) {14 console.log(e.data);15});16navigator.serviceWorker.controller.postMessage('Hello from the page!');17navigator.serviceWorker.addEventListener('message', function(e) {18 console.log(e.data);19});20navigator.serviceWorker.controller.postMessage('Hello from the page!');21navigator.serviceWorker.addEventListener('message', function(e) {22 console.log(e.data);23});24navigator.serviceWorker.controller.postMessage('Hello from the page!');25navigator.serviceWorker.addEventListener('message', function(e) {26 console.log(e.data);27});28navigator.serviceWorker.controller.postMessage('Hello from the page!');29navigator.serviceWorker.addEventListener('message', function(e) {30 console.log(e.data);31});32navigator.serviceWorker.controller.postMessage('Hello from the page!');33navigator.serviceWorker.addEventListener('message', function(e) {34 console.log(e.data);35});36navigator.serviceWorker.controller.postMessage('Hello from the page!');37navigator.serviceWorker.addEventListener('message', function(e) {38 console.log(e.data);39});40navigator.serviceWorker.controller.postMessage('Hello from the page!');41navigator.serviceWorker.addEventListener('message', function(e) {42 console.log(e.data);43});44navigator.serviceWorker.controller.postMessage('Hello from the page!');45navigator.serviceWorker.addEventListener('message', function(e) {46 console.log(e.data);47});48navigator.serviceWorker.controller.postMessage('Hello from the page!');

Full Screen

Using AI Code Generation

copy

Full Screen

1var availableWorkers = require('available-workers');2var worker = availableWorkers.observeWorker('worker.js', function(err, worker) {3});4var availableWorkers = require('available-workers');5var worker = availableWorkers.observeWorker('worker.js', function(err, worker) {6});7availableWorkers.stopObservingWorker(worker);8var availableWorkers = require('available-workers');9var worker = availableWorkers.getWorker('worker.js');10var availableWorkers = require('available-workers');11var workers = availableWorkers.getAllWorkers();12var availableWorkers = require('available-workers');13var workers = availableWorkers.getAvailableWorkers();14var availableWorkers = require('available-workers');15var workers = availableWorkers.getBusyWorkers();16var availableWorkers = require('available-workers');17var count = availableWorkers.getWorkerCount();

Full Screen

Using AI Code Generation

copy

Full Screen

1var availableWorkers = require('availableWorkers');2var workers = availableWorkers.observeWorker();3console.log(workers);4var availableWorkers = require('availableWorkers');5var worker = availableWorkers.getWorker('workerId');6console.log(worker);7var availableWorkers = require('availableWorkers');8var workers = availableWorkers.getWorkers();9console.log(workers);10var availableWorkers = require('availableWorkers');11var worker = availableWorkers.getWorker('workerId');12console.log(worker);13var availableWorkers = require('availableWorkers');14var worker = availableWorkers.getWorker('workerId');15console.log(worker);16var availableWorkers = require('availableWorkers');17var worker = availableWorkers.getWorker('workerId');18console.log(worker);19var availableWorkers = require('availableWorkers');20var worker = availableWorkers.getWorker('workerId');21console.log(worker);22var availableWorkers = require('availableWorkers');23var worker = availableWorkers.getWorker('workerId');24console.log(worker);25var availableWorkers = require('availableWorkers');26var worker = availableWorkers.getWorker('workerId');27console.log(worker);28var availableWorkers = require('availableWorkers');29var worker = availableWorkers.getWorker('workerId');30console.log(worker);31var availableWorkers = require('availableWorkers

Full Screen

Using AI Code Generation

copy

Full Screen

1var worker = require('worker');2var workerId = worker.observeWorker();3console.log(workerId);4var worker = require('worker');5var workerId = worker.observeWorker();6console.log(workerId);7> import ballerina.lang.system; 8> import ballerina.lang.worker;9> function main (string[] args) { 10> worker w1 { 11> workerId = worker.observeWorker(); 12> system:println(workerId); 13> } 14> worker w2 { 15> workerId = worker.observeWorker(); 16> system:println(workerId); 17> } 18> }19> import ballerina.lang.system; 20> import ballerina.lang.worker;21> function main (string[] args) { 22> worker w1 { 23> workerId = worker.observeWorker(); 24> system:println(workerId); 25> } 26> worker w2 { 27> workerId = worker.observeWorker(); 28> system:println(workerId); 29> } 30> }

Full Screen

Using AI Code Generation

copy

Full Screen

1import { availableWorkers } from 'worker-observer';2availableWorkers.observeWorker('worker-name', (worker) => {3});4import { availableWorkers } from 'worker-observer';5availableWorkers.registerWorker('worker-name');6import { availableWorkers } from 'worker-observer';7availableWorkers.unregisterWorker('worker-name');8import { availableWorkers } from 'worker-observer';9const isRegistered = availableWorkers.isRegistered('worker-name');10import { availableWorkers } from 'worker-observer';11const isObserved = availableWorkers.isObserved('worker-name');12import { availableWorkers } from 'worker-observer';13const worker = availableWorkers.getWorker('worker-name');14import { availableWorkers } from 'worker-observer';15const worker = availableWorkers.getWorkerByName('worker-name');16import { availableWorkers } from 'worker-observer';17const worker = availableWorkers.getWorkerById('worker-id');18import { availableWorkers } from 'worker-observer';19const worker = availableWorkers.getWorkerByIndex(0);20import { availableWorkers } from 'worker-observer';21const worker = availableWorkers.getWorkerByIndex(0);

Full Screen

Using AI Code Generation

copy

Full Screen

1availableWorkers.observeWorker('worker1').then(function(worker){2 console.log(worker);3});4availableWorkers.observeWorkers().then(function(workers){5 console.log(workers);6});7availableWorkers.observeWorkerNames().then(function(workerNames){8 console.log(workerNames);9});10availableWorkers.observeWorkerStatus('worker1').then(function(status){11 console.log(status);12});13availableWorkers.observeWorkerStatuses().then(function(statuses){14 console.log(statuses);15});16availableWorkers.observeWorkerStatusNames().then(function(statusNames){17 console.log(statusNames);18});

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