Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
1//--------------------------------------------------GLOBAL VARIABLES AND ELEMENTS---------------------------------------------2//global variables wich i use in functions without passing as paraments, or in this case juse for total calculating3let totalEl = document.querySelector('span.total-number')4const storeUl = document.querySelector("header .item-list")5const cartUl = document.querySelector("main .item-list")6const emptyCartBtn = document.querySelector('button.empty-cart-btn')7const sortPriceBtn = document.querySelector('button.store--btn-sort-price')8const sortAlphabetBtn = document.querySelector('button.store--btn-sort-alphabet')9const sortPriceBtnRemove = document.querySelector('button.store--btn-sort-price-remove')10//global variables button to filter by type11const filterTypeApricot = document.querySelector('button.store--btn-sort-filter-10')12const filterTypeBeetroot = document.querySelector('button.store--btn-sort-filter-1')13const filterTypeCarrot = document.querySelector('button.store--btn-sort-filter-2')14const filterTypeApple = document.querySelector('button.store--btn-sort-filter-3')15const filterTypeAvocado = document.querySelector('button.store--btn-sort-filter-4')16const filterTypeBanana = document.querySelector('button.store--btn-sort-filter-5')17const filterTypeBellPepper = document.querySelector('button.store--btn-sort-filter-6')18const filterTypeBerry = document.querySelector('button.store--btn-sort-filter-7')19const filterTypeBlueBerry = document.querySelector('button.store--btn-sort-filter-8')20const filterTypeEggPlant = document.querySelector('button.store--btn-sort-filter-9')21// const filterAllBtn = document.querySelectorAll('button.store--btn-sort-filter')22//----------------------------------------------END OF GLOBAL VARIABLES-----------------------------------------------------------23//----------------------------------------------START OF STATE OBJECT--------------------------------------------------------------24//state object, has an array items wich itself has lots of objects inside with 4 properties wich are updated and used in the app25const state = {26 //commented because i load them from server now27 // items: [28 // {29 // id: 1,30 // name: 'beetroot',31 // price: 6.78,32 // inStock: 30,33 // inCart: 0,34 // filterOnly: false35 // },36 // {37 // id: 2,38 // name: 'carrot',39 // price: 0.75,40 // inStock: 30,41 // inCart: 0,42 // filterOnly: false43 // },44 // {45 // id: 3,46 // name: 'apple',47 // price: 0.55,48 // inStock: 30,49 // inCart: 0,50 // filterOnly: false51 // },52 // {53 // id: 4,54 // name: 'apricot',55 // price: 0.25,56 // inStock: 30,57 // inCart: 0,58 // filterOnly: false59 // },60 // {61 // id: 5,62 // name: 'avocado',63 // price: 1.25,64 // inStock: 30,65 // inCart: 0,66 // filterOnly: false67 // },68 // {69 // id: 6,70 // name: 'bananas',71 // price: 1.70,72 // inStock: 30,73 // inCart: 0,74 // filterOnly: false75 // },76 // {77 // id: 7,78 // name: 'bell-pepper',79 // price: 7.55,80 // inStock: 30,81 // inCart: 0,82 // filterOnly: false83 // },84 // {85 // id: 8,86 // name: 'berry',87 // price: 9.90,88 // inStock: 30,89 // inCart: 0,90 // filterOnly: false91 // },92 // {93 // id: 9,94 // name: 'blueberry',95 // price: 4.50,96 // inStock: 30,97 // inCart: 0,98 // filterOnly: false99 // },100 // {101 // id: 10,102 // name: 'eggplant',103 // price: 5.75,104 // inStock: 30,105 // inCart: 0,106 // filterOnly: false107 // }108 // ],109 priceOrderBy: [], //this will have objects from items in state ordered by price in rerendering etc feature works110 alphabetOrderBy: [], //the same as above111 orderByPrice: false, //this is what trigers wether we will have to render in order or not112 orderByAlphabet: false,113 filter: false114 115}116// function pushToOtherArrays() {117// state.priceOrderBy.push(...state.items); //now both are the same spread operator copy array118// state.alphabetOrderBy.push(...state.items); //now both are the same spread operator copy array119// }120//------------------------------------------------END OF STATE OBJECT------------------------------------------------------------------121//------------------------------------------SERVER FUNCTIONS--------------------------------------------------------------122function getStateDataFromServer() {123 return fetch('http://localhost:3000/items').then(function (response) 124 {125 return response.json()126 })127}128//-------------------------------------------END OF SERVER FUNCTIONS----------------------------------------------------------129/* const priceOrderDescending = state.items.sort((b, a) => (b.price > a.price) ? 1 : (b.price === a.price) ? ((b.name > a.name) ? 1 : -1) : -1 )130 console.log(priceOrderDescending)131 Questions to answer132 Q: What items are in the store? â
133 A: state.items134 Q: What items are in my cart? â
135 A: getCartItems()136 Q: How many of each item do I have? â
137 A: state.items.inCart138 Q: How much do I have to pay? â
139 A: getCalculateTotal()140 Q: How many items are in stock? â
141 A: state.items.inStock */142//-------------------------------------------HELPER FUNCTIONS DERIVED STATE---------------------------------------------------------------143//function that sorts by alphabet uses state.alphabetOrderBy144function sortByAlphabet() {145 //or do it with arrow functions146 state.alphabetOrderBy.sort(function(a, b){147 if(a.name < b.name) { return -1; }148 if(a.name > b.name) { return 1; }149 return 0;150 })151 state.orderByAlphabet = true152 state.orderByPrice = false153 render()154}155//function that uses sorts by alphabet156function getEventListenerBtnSortAlphabet() {157 sortAlphabetBtn.addEventListener('click', function(event) {158 event.preventDefault()159 sortByAlphabet()160 })161}162//this function gets the ordered array in the state163function getOrderedStore() {164 // state.priceOrderBy = state.items.sort((a, b) => (a.price > b.price) ? 1 : (a.price === b.price) ? ((a.name > b.name) ? 1 : -1) : -1 ) //this changes original array thats why revert button didnt work165 state.priceOrderBy.sort((a, b) => (a.price > b.price) ? 1 : (a.price === b.price) ? ((a.name > b.name) ? 1 : -1) : -1 )166 state.orderByPrice = true167 state.orderByAlphabet = false168 render()169}170//this function gets the previous orderes array by changing state and rerender171function getEventListenerRevertBackOrder() {172 sortPriceBtnRemove.addEventListener('click', function(event) {173 event.preventDefault()174 changeOrderByPrice()175 })176}177//helper for the event listener to rever order price back to previous state178function changeOrderByPrice() {179 state.orderByPrice = false180 state.orderByAlphabet = false181 state.filter = false182 render()183}184//this function just is part of init() and gets ordered calls the function there185function getEventListenerBtnSortPrice() {186 sortPriceBtn.addEventListener('click', function(event) {187 event.preventDefault()188 getOrderedStore()189 })190}191//function wich contains all 10 event listeners for 10 btn filters by type192function getEventListenerFilterButtons() {193 filterTypeApple.addEventListener('click', function(event) {194 event.preventDefault()195 state.filter = true196 for (const element of state.items) {197 if (element.name === 'apple') {198 element.filterOnly = true199 render()200 }201 }202 })203 filterTypeApricot.addEventListener('click', function(event) {204 event.preventDefault()205 state.filter = true206 for (const element of state.items) {207 if (element.name === 'apricot') {208 element.filterOnly = true209 render()210 }211 }212 213 })214 filterTypeAvocado.addEventListener('click', function(event) {215 event.preventDefault()216 state.filter = true217 for (const element of state.items) {218 if (element.name === 'avocado') {219 element.filterOnly = true220 render()221 }222 }223 224 })225 filterTypeBanana.addEventListener('click', function(event) {226 event.preventDefault()227 state.filter = true228 for (const element of state.items) {229 if (element.name === 'bananas') {230 element.filterOnly = true231 render()232 }233 }234 235 })236 filterTypeBeetroot.addEventListener('click', function(event) {237 event.preventDefault()238 state.filter = true239 for (const element of state.items) {240 if (element.name === 'beetroot') {241 element.filterOnly = true242 render()243 }244 }245 246 })247 filterTypeBellPepper.addEventListener('click', function(event) {248 event.preventDefault()249 state.filter = true250 for (const element of state.items) {251 if (element.name === 'bell-pepper') {252 element.filterOnly = true253 render()254 }255 }256 257 })258 filterTypeBerry.addEventListener('click', function(event) {259 event.preventDefault()260 state.filter = true261 for (const element of state.items) {262 if (element.name === 'berry') {263 element.filterOnly = true264 render()265 }266 }267 268 })269 filterTypeBlueBerry.addEventListener('click', function(event) {270 event.preventDefault()271 state.filter = true272 for (const element of state.items) {273 if (element.name === 'blueberry') {274 element.filterOnly = true275 render()276 }277 }278 279 })280 filterTypeEggPlant.addEventListener('click', function(event) {281 event.preventDefault()282 state.filter = true283 for (const element of state.items) {284 if (element.name === 'eggplant') {285 element.filterOnly = true286 render()287 }288 }289 290 })291 filterTypeCarrot.addEventListener('click', function(event) {292 event.preventDefault()293 state.filter = true294 for (const element of state.items) {295 if (element.name === 'carrot') {296 element.filterOnly = true297 render()298 }299 }300 301 })302}303//function that stores all true filter only in state.items array i need for events of buttons filter by304function getFilterByState() {305 return state.items.filter(item => item.filterOnly === true)306}307//this is a function in wich when i click a new feature added button the whole cart item get erased by manipulating the STATE308function emptyCartBtnEvent() {309 for (const element of state.items) {310 const saveCartQuantity = element.inCart311 element.inCart = 0312 element.inStock += saveCartQuantity313 }314}315//this function just clears all cart items when clicked as an event listener and calls function inside it316function listenToEmptyCartBtn() {317 emptyCartBtn.addEventListener('click', function () {318 emptyCartBtnEvent()319 render()320 })321}322//the key function to make rendering work as it should323function getCartItems() {324 return state.items.filter(item => item.inCart > 0) //filter is a method for ARRAYS to filter and create a new ARRAY325 /* arrow function function (item) {326 return item.inCart > 0327 } 328 */329}330//this is called when i click the small btn minus in cart item section, and updates the states331function decreaseItemQuantity(cardParam) {332 if (cardParam.inCart > 0) {333 cardParam.inCart--334 cardParam.inStock++335 }336}337//this is called when i click the small btn plus in cart item section, and updates the states338function increaseItemQuantity(cardParam) {339 if (cardParam.inStock > 0) {340 cardParam.inStock--341 cardParam.inCart++342 }343}344//this function calculates the total and rerenders when state changes345function calculateTotal() {346 let total = 0347 const cartArray = getCartItems()348 for (const element of cartArray) {349 total += element.price * element.inCart350 }351 return total352}353//this function crucial to make the x button feature work354function removeItemFromStore(removeParam) {355 const updatedStore = state.items.filter(storeParam => storeParam.id !== removeParam.id)356 state.items = updatedStore357}358//-----------------------------------------END OF HELPER FUNCTIONS------------------------------------------------------359//----------------------------------------RENDER FUNCTIONS------------------------------------------------------------------------360//function to call the renderStoreItem for the header items to fill out in a for with argument an array from state361function renderStore(itemsParam, priceParam, alphabetParam) {362 //just has a for of loop, because i have an array parameter and want to call store header items363 //we get the ul wich i want from header DESTROY THEN RECREATE364 storeUl.innerHTML = ''365 const filterArray = getFilterByState()366 //we create here individual store item so 10 will be shown each time you rerender and destroy then render etc367 if (state.orderByPrice === false && state.orderByAlphabet === false && state.filter === false) {368 for (const element of itemsParam) {369 renderStoreItem(element)370 }371 }372 else if(state.orderByPrice === true && state.orderByAlphabet === false && state.filter === false) {373 for (const element of priceParam) {374 renderStoreItem(element)375 }376 }377 else if(state.orderByPrice === false && state.orderByAlphabet === true && state.filter === false) {378 for (const element of alphabetParam) {379 renderStoreItem(element)380 }381 }382 else if(state.orderByPrice === false && state.orderByAlphabet === false && state.filter === true) {383 for (const element of filterArray) {384 renderStoreItem(element)385 }386 }387}388//this functions calls the above function in the btn eventlistener, and this renders all items in the header part the 10 elements in the store389function renderStoreItem(storeParam) {390 //creating li391 const liEl = document.createElement('li')392 393 //creating a div394 const divEl = document.createElement('div')395 divEl.setAttribute('class', 'store--item-icon')396 //creating a btn with x to remove el from store397 const removeBtnEl = document.createElement('button')398 removeBtnEl.textContent = 'X'399 removeBtnEl.addEventListener('click', function(event) {400 event.preventDefault()401 removeItemFromStore(storeParam)402 render()403 })404 405 //creating an image406 const imgEl = document.createElement('img')407 //checking that the id 10 should have different src image string408 if (storeParam.id === 10) {409 imgEl.setAttribute('src', `assets/icons/0${storeParam.id}-${storeParam.name}.svg`)410 }411 //for the other from id 1-9 wich has an 00412 else {413 imgEl.setAttribute('src', `assets/icons/00${storeParam.id}-${storeParam.name}.svg`)414 }415 imgEl.setAttribute('alt', storeParam.name)416 //creating a button wich is crucial to this app417 const btnEl = document.createElement('button')418 btnEl.textContent = 'Add to cart'419 //creating span to show me the item if is in stock and how many420 const stockSpanEl = document.createElement('span')421 stockSpanEl.setAttribute('class', 'stock-span-store')422 stockSpanEl.textContent = `The stock: ${storeParam.inStock}`423 //creating span to show me the item price424 const priceSpanEl = document.createElement('span')425 priceSpanEl.setAttribute('class', 'price-span-store')426 priceSpanEl.textContent = `The price: ${storeParam.price}`427 //creating span to show me the item name428 const nameSpanEl = document.createElement('span')429 nameSpanEl.setAttribute('class', 'name-span-store')430 nameSpanEl.textContent = `Name: ${storeParam.name}`431 //appending in order432 divEl.append(imgEl)433 liEl.append(removeBtnEl, divEl, btnEl, stockSpanEl, priceSpanEl, nameSpanEl)434 storeUl.append(liEl)435 //event listeners for the add to cart button436 btnEl.addEventListener('click', function(event) {437 event.preventDefault()438 increaseItemQuantity(storeParam)439 calculateTotal()440 render()441 })442}443//this function render the cart in the main html444function renderCart() {445 //just has a for of loop, because i have an array parameter and want to call store header items446 //we get the ul wich i want from header DESTROY447 cartUl.innerHTML = ''448 // then, recreate the contents of the cart FILTER ARRAY THIS RETURNED THING449 const cart = getCartItems() //KEY TO MAKE THINGS WORK450 for (const element of cart) {451 renderCartItem(element)452 }453}454//function to call renderCartItem this is called only when the btn in add to cart in renderStoreItem is clicked, problems here in rerendering455function renderCartItem(cartParam) {456 //creating the li457 const liEl = document.createElement('li')458 //creating the img459 const imgEl = document.createElement('img')460 imgEl.setAttribute('class', 'cart--item-icon')461 //checking if the id 10 will have the 0 not 00 cause then it doesnt load462 if (cartParam.id === 10) {463 imgEl.setAttribute('src', `assets/icons/0${cartParam.id}-${cartParam.name}.svg`)464 }465 //other wich from id 1-9466 else {467 imgEl.setAttribute('src', `assets/icons/00${cartParam.id}-${cartParam.name}.svg`)468 }469 imgEl.setAttribute('alt', `${cartParam.name}`)470 //creating the p element471 const pEl = document.createElement('p')472 //creating the btn element the first one with -473 const btnEl1 = document.createElement('button')474 btnEl1.setAttribute('class' , 'quantity-btn remove-btn center')475 btnEl1.textContent = '-'476 477 //creating span element wich has the value when you change the btn + or -478 const spanEl = document.createElement('span')479 spanEl.setAttribute('class', 'quantity-text center')480 spanEl.textContent = cartParam.inCart481 //creating btn2 wich creates this button for +482 const btnEl2 = document.createElement('button')483 btnEl2.setAttribute('class', 'quantity-btn add-btn center')484 btnEl2.textContent = '+'485 //appending things and ul is created totally486 liEl.append(imgEl, pEl, btnEl1, spanEl, btnEl2)487 cartUl.append(liEl)488 //event listeners butttons the 1 and 2 - and +489 btnEl1.addEventListener('click', function(event) {490 event.preventDefault()491 decreaseItemQuantity(cartParam)492 spanEl.textContent = cartParam.inCart493 // if (cardImgParam.inCart === 0) {494 // liEl.remove() YOU DONT NEED THIS YOU HAVE STATE NO DOM495 // }496 calculateTotal()497 render()498 })499 btnEl2.addEventListener('click', function(event) {500 event.preventDefault()501 increaseItemQuantity(cartParam)502 spanEl.textContent = cartParam.inCart503 calculateTotal()504 render()505 })506}507//function that renders the total span after each rerender508function renderTotal() {509 totalEl.textContent = '£' + calculateTotal().toFixed(2)510}511//calls everything, rerenders the page and does all512function render() {513 renderStore(state.items, state.priceOrderBy, state.alphabetOrderBy)514 renderCart()515 renderTotal()516}517// change state >>> rerender518function init() {519 render()520 listenToEmptyCartBtn()521 // pushToOtherArrays()522 getEventListenerBtnSortPrice()523 getEventListenerRevertBackOrder()524 getEventListenerBtnSortAlphabet()525 getEventListenerFilterButtons()526}527//----------------------------------------------------END OF RENDER FUNCTIONS------------------------------------------------------528//crucial to get data from json server rest api then to load them in state object those wich i need, now all is in server529getStateDataFromServer().then(function (itemsFromServer) {530 state.items = itemsFromServer531 state.priceOrderBy.push(...state.items); //now both are the same spread operator copy array532 state.alphabetOrderBy.push(...state.items); //now both are the same spread operator copy array533 init() // no need to call it this basically starts the code running534})535//----------------------------------------------------FUNCTION CALL------------------------------------------------------------------536//the only function call in main, then everything renders here with function calls...
DataService.js
Source:DataService.js
1function DataService() {2 this.URL_SEPARATOR = '/';3}4DataService.prototype = {5 // Make synchronous get call6 getDataSynchronous: function(url, data) {7 var results = undefined;8 $.ajax({9 url: url,10 data: data,11 type: 'get',12 dataType: 'json',13 async: false,14 success: function(data) {15 results = data;16 },17 error: function(e) {18 }19 });20 return results;21 },22 /**23 * Makes an asynchronous GET request to the back end,24 * generates a spinner in the UI25 * execute a callback function on the result of the request,26 * @param {string} url url of the request27 * @param {string} data query string data28 * @param {Function} callback function to be called after the request29 * @param {string} spinArea id of the spinner element30 * @return {[type]} [description]31 */32 getDataAsynchronous: function(url, data, callback, spinArea) {33 const target = document.getElementById(spinArea);34 const spinner = new Spinner().spin(target);35 let results;36 return $.ajax({37 url: url,38 data: data,39 type: 'get',40 dataType: 'json',41 success: function(data) {42 results = data;43 },44 error: function(e) {45 }46 }).done(function(data){47 if (callback) {48 callback(data);49 } else {50 return data;51 }52 }).always(function(data) {53 spinner.stop();54 });55 },56 // Make post call57 postData: function(url, data) {58 return $.ajax({59 url: url,60 headers: {61 'Accept': 'application/json',62 'Content-Type': 'application/json'63 },64 type: 'post',65 dataType: 'json',66 data: data67 });68 },69 // FIXME: Tried to put spinner in ajax call, so that each page wont have to handle it separately, as long as 'spin-area' div is placed70 // However, spinner doesn't work if generic 'spin-area' div is placed on all pages (usually doesn't load on anomaly results page when landing on it 2nd time)71 // Hence I've put on each page, a different div id, and that id is passed to the ajax call72 // TODO: Either figure out why generic div id won't work (because passing div id to the ajax caller isn't the best in terms of role separation)73 // Or handle spinner on each page separately (I don't prefer this approach because duplication of logic everywhere)74 fetchMetricSummary: function(dashboard, timeRange, callback) {75 var url = constants.METRIC_SUMMARY;76 var data = {77 dashboard : dashboard,78 timeRange : timeRange79 };80 this.getDataAsynchronous(url, data, callback, 'summary-spin-area');81 },82 fetchAnomalySummary: function(dashboard, timeRanges, callback) {83 var url = constants.ANOMALY_SUMMARY;84 var data = {85 dashboard : dashboard,86 timeRanges : timeRanges.join()87 };88 this.getDataAsynchronous(url, data, callback, 'summary-spin-area');89 },90 fetchWowSummary: function(dashboard, timeRanges, callback) {91 var url = constants.WOW_SUMMARY;92 var data = {93 dashboard : dashboard,94 timeRanges : timeRanges.join()95 };96 this.getDataAsynchronous(url, data, callback, 'summary-spin-area');97 },98 /**99 * Wrapper for all back end search requests100 * @param {Object} args arguments needed to perform the search101 * @return {Object} result payload102 */103 fetchAnomalies(args = {}) {104 const {105 anomaliesSearchMode,106 startDate,107 endDate,108 pageNumber,109 metricIds,110 dashboardId,111 anomalyIds,112 anomalyGroupIds,113 functionName,114 updateModelAndNotifyView,115 filterOnly,116 spinner117 } = args;118 switch(anomaliesSearchMode) {119 case constants.MODE_TIME:120 return this.fetchAnomaliesForTime(startDate, endDate, pageNumber, filterOnly, updateModelAndNotifyView, spinner);121 case constants.MODE_METRIC:122 if (!metricIds || !metricIds.length) return;123 return this.fetchAnomaliesForMetricIds(startDate, endDate, pageNumber, metricIds, functionName, filterOnly, updateModelAndNotifyView, spinner);124 case constants.MODE_DASHBOARD:125 if (!dashboardId || !dashboardId.length) return;126 return this.fetchAnomaliesForDashboardId(startDate, endDate, pageNumber, dashboardId, functionName, filterOnly, updateModelAndNotifyView, spinner);127 case constants.MODE_ID:128 if (!anomalyIds || !anomalyIds.length) return;129 return this.fetchAnomaliesForAnomalyIds(startDate, endDate, pageNumber, anomalyIds, functionName, filterOnly, updateModelAndNotifyView, spinner);130 case constants.MODE_GROUPID:131 if (!anomalyGroupIds || !anomalyGroupIds.length) return;132 return this.fetchAnomaliesforGroupIds(startDate, endDate, pageNumber, anomalyGroupIds, functionName, filterOnly, updateModelAndNotifyView, spinner);133 default:134 return;135 }136 },137 // Fetch anomalies for metric ids in array in time range138 fetchAnomaliesForMetricIds : function(startTime, endTime, pageNumber, metricIds, functionName, filterOnly, callback, spinner) {139 const url = constants.SEARCH_ANOMALIES_METRICIDS + startTime + this.URL_SEPARATOR + endTime + this.URL_SEPARATOR + pageNumber;140 const data = {141 metricIds: metricIds,142 functionName,143 filterOnly144 };145 return this.getDataAsynchronous(url, data, callback, 'anomaly-spin-area');146 },147 // Fetch anomalies for dashboard id in time range148 fetchAnomaliesForDashboardId : function(startTime, endTime, pageNumber, dashboardId, functionName, filterOnly, callback, spinner) {149 const url = constants.SEARCH_ANOMALIES_DASHBOARDID + startTime + this.URL_SEPARATOR + endTime + this.URL_SEPARATOR + pageNumber;150 const data = {151 dashboardId,152 functionName,153 filterOnly154 };155 return this.getDataAsynchronous(url, data, callback, 'anomaly-spin-area');156 },157 // Fetch anomalies for anomaly ids in array in time range158 fetchAnomaliesForAnomalyIds : function(startTime, endTime, pageNumber, anomalyIds, functionName, filterOnly, callback, spinner) {159 const url = constants.SEARCH_ANOMALIES_ANOMALYIDS + startTime + this.URL_SEPARATOR + endTime + this.URL_SEPARATOR + pageNumber;160 const data = {161 anomalyIds,162 functionName,163 filterOnly164 };165 return this.getDataAsynchronous(url, data, callback, spinner);166 },167 // Fetch anomalies for group ids in array168 fetchAnomaliesforGroupIds(startTime, endTime, pageNumber, anomalyGroupIds, functionName, filterOnly, callback, spinner) {169 const url = constants.SEARCH_ANOMALIES_GROUPIDS + startTime + this.URL_SEPARATOR + endTime + this.URL_SEPARATOR + pageNumber;170 var data = {171 anomalyGroupIds,172 functionName,173 filterOnly174 };175 this.getDataAsynchronous(url, data, callback, 'anomaly-spin-area');176 },177 // Fetch anomalies for anomaly ids in array in time range178 fetchAnomaliesForTime : function(startTime, endTime, pageNumber, filterOnly, callback, spinner) {179 const url = constants.SEARCH_ANOMALIES_TIME + startTime + this.URL_SEPARATOR + endTime + this.URL_SEPARATOR + pageNumber;180 const data = {181 filterOnly182 };183 return this.getDataAsynchronous(url, data, callback, spinner);184 },185 // Update anomaly feedback for anomaly id186 updateFeedback : function(anomalyId, feedbackType, comment) {187 var url = constants.UPDATE_ANOMALY_FEEDBACK + anomalyId;188 const data = {189 feedbackType,190 comment191 };192 var response = this.postData(url, JSON.stringify(data));193 },194 fetchGranularityForMetric(metricId) {195 const url = constants.METRIC_GRANULARITY + metricId;196 return this.getDataAsynchronous(url);197 },198 fetchDimensionsForMetric(metricId) {199 const url = constants.METRIC_DIMENSION + metricId;200 return this.getDataAsynchronous(url);201 },202 fetchFiltersForMetric(metricId) {203 const url = constants.METRIC_FILTERS + metricId;204 return this.getDataAsynchronous(url);205 },206 fetchMaxTimeForMetric(metricId) {207 const url = constants.METRIC_MAX_TIME + metricId;208 return this.getDataAsynchronous(url);209 },210 fetchTimeseriesCompare: function (metricId, currentStart, currentEnd, baselineStart, baselineEnd,211 dimension = "ALL", filters = {}, granularity = "DAYS") {212 var url = "/timeseries/compare/" + metricId + "/" + currentStart + "/" + currentEnd + "/"213 + baselineStart + "/" + baselineEnd + "?dimension=" + dimension + "&filters="214 + encodeURIComponent(JSON.stringify(filters)) + "&granularity=" + granularity;215 return this.getDataAsynchronous(url, {}, null, 'analysis-graph-spin-area');216 },217 fetchHeatmapData: function (metricId, currentStart, currentEnd, baselineStart, baselineEnd,218 filters = {}) {219 var url = "/data/heatmap/" + metricId + "/" + currentStart + "/" + currentEnd + "/"220 + baselineStart + "/" + baselineEnd + "?filters=" + encodeURIComponent(JSON.stringify(filters));221 return this.getDataAsynchronous(url, {}, null, 'dimension-tree-spin-area');222 },223 fetchAnomalyWowData(anomalyId){224 const url = `/anomalies/${anomalyId}`;225 return this.getDataSynchronous(url);226 },227 fetchMetricByMetricId(metricId) {228 const url = `/data/metric/${metricId}`;229 return this.getDataSynchronous(url);230 },231 fetchRootCauseData(currentStart, baselineStart, windowSize, inputUrn) {232 const url = `/rootcause/query?framework=rootCause¤t=${currentStart}&baseline=${baselineStart}&windowSize=${windowSize}&urns=${inputUrn}`;233 return this.getDataAsynchronous(url, {}, null, 'rootcause-table-spin-area');234 }...
TableHeader.js
Source:TableHeader.js
1import React, { Component } from 'react';2import {HeaderCell} from './HeaderCell';3export class TableHeader extends Component {4 createHeaderCells(columns, renderOptions) {5 return React.Children.map(columns, (column, i) => {6 return <HeaderCell key={column.columnKey||column.field||i} columnProps={column.props} value={this.props.value} onSort={this.props.onSort}7 sortField={this.props.sortField} sortOrder={this.props.sortOrder} multiSortMeta={this.props.multiSortMeta}8 resizableColumns={this.props.resizableColumns} onColumnResizeStart={this.props.onColumnResizeStart}9 onFilter={this.props.onFilter} renderOptions={renderOptions} onHeaderCheckboxClick={this.props.onHeaderCheckboxClick} headerCheckboxSelected={this.props.headerCheckboxSelected}10 reorderableColumns={this.props.reorderableColumns} onDragStart={this.props.onColumnDragStart} onDragOver={this.props.onColumnDragOver}11 onDragLeave={this.props.onColumnDragLeave} onDrop={this.props.onColumnDrop} filters={this.props.filters} tabIndex={this.props.tabIndex} />;12 });13 }14 hasColumnFilter(columns) {15 if (columns) {16 for (let col of columns) {17 if (col.props.filter) {18 return true;19 }20 }21 }22 return false;23 }24 render() {25 let content;26 if (this.props.columnGroup) {27 let rows = React.Children.toArray(this.props.columnGroup.props.children);28 content = rows.map((row, i) => {29 return <tr key={i} role="row">{this.createHeaderCells(React.Children.toArray(row.props.children), {filterOnly: false, renderFilter: true, renderHeaderCheckbox: true})}</tr>;30 });31 }32 else {33 let columns = React.Children.toArray(this.props.children);34 if (this.hasColumnFilter(columns)) {35 content = (36 <>37 <tr role="row">{this.createHeaderCells(columns, {filterOnly: false, renderFilter: false, renderHeaderCheckbox: false})}</tr>38 <tr role="row">{this.createHeaderCells(columns, {filterOnly: true, renderFilter: true, renderHeaderCheckbox: true})}</tr>39 </>40 );41 }42 else {43 content = <tr role="row">{this.createHeaderCells(columns, {filterOnly: false, renderFilter: false, renderHeaderCheckbox: true})}</tr>;44 }45 }46 return (47 <thead className="p-datatable-thead">48 {content}49 </thead>50 );51 }...
winston.middleware.js
Source:winston.middleware.js
...17 verbose: 4,18 debug: 5,19 silly: 620};21function filterOnly(level) {22 return format(info => {23 if (info[LEVEL] === level)24 return info;25 })();26}27// Create a new winston logger instance with two transports: Console, and File28const logger = createLogger({29 levels: customLevels,30 transports: [31 new transports.Console({ handleExceptions: false, level: 'info' }),32 new transports.File({33 filename: errorFile, level: 'error', maxsize: 52428800, maxFiles: 50, format: filterOnly('error')34}),35 new transports.File({36 filename: warnFile, level: 'warn', maxsize: 52428800, maxFiles: 20, format: filterOnly('warn')37}),38 new transports.File({39 filename: infoFile, level: 'info', maxsize: 52428800, maxFiles: 20, format: filterOnly('info')40}),41 new transports.File({42 filename: verboseFile, level: 'verbose', maxsize: 52428800, maxFiles: 20, format: filterOnly('verbose')43}),44 new transports.File({45 filename: debugFile, level: 'debug', maxsize: 52428800, maxFiles: 20, format: filterOnly('debug')46}),47 new transports.File({48 filename: sillyFile, level: 'silly', maxsize: 52428800, maxFiles: 20, format: filterOnly('silly')49}),50 new transports.File({51 filename: mailFile, level: 'mail', maxsize: 52428800, maxFiles: 20, format: filterOnly('mail')52}),53 new transports.File({54 filename: mailErrorFile, level: 'mailError', maxsize: 52428800, maxFiles: 20, format: filterOnly('mailError')55})56 ],57 exitOnError: false58});59logger.stream = {60 write: (message, encoding) => {61 logger.info(message);62 }63};...
data.js
Source:data.js
1export default 2 [3 {4 id: 1,5 name: "beetroot",6 price: 6.78,7 inStock: 30,8 inCart: 0,9 filterOnly: false,10 image: '001-beetroot.svg'11 },12 {13 id: 2,14 name: "carrot",15 price: 0.75,16 inStock: 30,17 inCart: 0,18 filterOnly: false,19 image: '002-carrot.svg'20 },21 {22 id: 3,23 name: "apple",24 price: 0.55,25 inStock: 30,26 inCart: 0,27 filterOnly: false,28 image: '003-apple.svg'29 },30 {31 id: 4,32 name: "apricot",33 price: 0.25,34 inStock: 30,35 inCart: 0,36 filterOnly: false,37 image: '004-apricot.svg'38 },39 {40 id: 5,41 name: "avocado",42 price: 1.25,43 inStock: 30,44 inCart: 0,45 filterOnly: false,46 image: '005-avocado.svg'47 },48 {49 id: 6,50 name: "bananas",51 price: 1.7,52 inStock: 30,53 inCart: 0,54 filterOnly: false,55 image: '006-bananas.svg'56 },57 {58 id: 7,59 name: "bell-pepper",60 price: 7.55,61 inStock: 30,62 inCart: 0,63 filterOnly: false,64 image: '007-bell-pepper.svg'65 },66 {67 id: 8,68 name: "berry",69 price: 9.9,70 inStock: 30,71 inCart: 0,72 filterOnly: false,73 image: '008-berry.svg'74 },75 {76 id: 9,77 name: "blueberry",78 price: 4.5,79 inStock: 30,80 inCart: 0,81 filterOnly: false,82 image: '009-blueberry.svg'83 },84 {85 id: 10,86 name: "eggplant",87 price: 5.75,88 inStock: 30,89 inCart: 0,90 filterOnly: false,91 image: '010-eggplant.svg'92 }...
GridHelper.js
Source:GridHelper.js
1Ext.define('CMDBuildUI.util.administration.helper.GridHelper', {2 singleton: true,3 /**4 * Filter grid items.5 * @param {CMDBuildUI.store.Base} store6 * @param {string} searchTerm7 * @param {Array} filterOnly //Array of fieldnames8 */ 9 searchMoreFields: function (store, searchTerm, filterOnly) {10 store.filter(function (record) {11 var data = record.getData();12 var result = false;13 for (var key in data) {14 if ((filterOnly && filterOnly.includes(key)) || !filterOnly) {15 if (String(data[key]).toLowerCase().includes(searchTerm.toLowerCase())) {16 result = true;17 }18 }19 }20 return result;21 });22 }...
logger.js
Source:logger.js
...14 json()15 ),16 transports: [17 new winston.transports.Console({ level: 'info' }),18 // new winston.transports.File({ filename: 'debug.log', level: 'debug', format: filterOnly('debug') }),19 new winston.transports.File({ filename: './logs/warn.log', format: filterOnly('warn') }),20 new winston.transports.File({ filename: './logs/error.log', format: filterOnly('error') })21 ]22 })...
loger.js
Source:loger.js
...14 json()15 ),16 transports: [17 new winston.transports.Console({ level: 'info' }),18 new winston.transports.File({ filename: './logs/warn.log', format: filterOnly('warn') }),19 new winston.transports.File({ filename: './logs/error.log', format: filterOnly('error') })20 ]21})...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!