Best JavaScript code snippet using wpt
service-worker.js
Source:service-worker.js
1importScripts("/js/helpers.js", "https://unpkg.com/idb@2.1.3/lib/idb.js");2const staticCacheName = "restaurant-reviews-static-v5";3const restaurantImagesCache = "restaurant-reviews-restaurant-images";4const mapboxTilesCache = "restaurant-reviews-map-tiles";5const fontsCache = "restaurant-reviews-fonts";6const fontAwesomeCache = "font-awesome";7const allCaches = [8 staticCacheName,9 restaurantImagesCache,10 mapboxTilesCache,11 fontsCache,12 fontAwesomeCache,13];14self.addEventListener("install", (event) => {15 event.waitUntil(16 caches17 .open(staticCacheName)18 .then((cache) =>19 cache.addAll([20 "/",21 "/restaurant.html",22 "/css/restaurant-details.css",23 "/css/restaurants-list.css",24 "/js/helpers.js",25 "/js/main.js",26 "/js/restaurant_info.js",27 "/img/offline.svg",28 "/img/offline_wide.svg",29 "/img/spinner.gif",30 "/img/restaurant_map_tiny.png",31 "/img/restaurants_map_tiny.png",32 "https://unpkg.com/idb@2.1.3/lib/idb.js",33 "https://use.fontawesome.com/releases/v5.5.0/css/all.css",34 "https://unpkg.com/leaflet@1.3.1/dist/leaflet.css",35 "https://unpkg.com/leaflet@1.3.1/dist/leaflet.js",36 "https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,700",37 "https://unpkg.com/leaflet@1.3.1/dist/images/marker-icon.png",38 "https://unpkg.com/leaflet@1.3.1/dist/images/marker-icon-2x.png",39 "https://unpkg.com/leaflet@1.3.1/dist/images/marker-shadow.png",40 ])41 )42 .catch((error) => console.log(error))43 );44});45self.addEventListener("activate", (event) => {46 // delete the old versions of the cache47 event.waitUntil(48 caches49 .keys()50 .then((cacheNames) =>51 Promise.all(52 cacheNames53 .filter(54 (cacheName) =>55 cacheName.startsWith("restaurant-reviews-") &&56 !allCaches.includes(cacheName)57 )58 .map((cacheName) => caches.delete(cacheName))59 )60 )61 .catch((error) => console.log(error))62 );63 self.clients.claim();64});65const dbPromise = openDatabase(true);66self.addEventListener("message", (event) => {67 if (event.data.type === "post-review") {68 const { review, requestId } = event.data;69 dbPromise.then((db) => {70 const outboxStore = db71 .transaction("outbox", "readwrite")72 .objectStore("outbox");73 outboxStore.put({ ...review, request_id: requestId });74 self.registration.sync.register(requestId);75 });76 }77});78self.addEventListener("sync", (event) => {79 event.waitUntil(80 dbPromise.then((db) => {81 const requestId = event.tag;82 let outboxStore = db.transaction("outbox").objectStore("outbox");83 outboxStore.get(requestId).then((request) => {84 const { restaurant_id, name, rating, comments } = request;85 return DBHelper.addReview(86 restaurant_id,87 name,88 rating,89 comments,90 (error, newReview) => {91 if (error) {92 // broadcast update to all clients93 self.clients.matchAll().then((clients) => {94 clients.forEach((client) => {95 client.postMessage({96 type: "update-review",97 error: true,98 requestId,99 });100 });101 });102 // delete review from outbox store103 outboxStore = db104 .transaction("outbox", "readwrite")105 .objectStore("outbox");106 outboxStore.delete(requestId);107 } else {108 // broadcast update to all clients109 self.clients.matchAll().then((clients) => {110 clients.forEach((client) => {111 client.postMessage({112 type: "update-review",113 review: newReview,114 requestId,115 });116 });117 });118 // add review to reviews store119 const reviewsStore = db120 .transaction("reviews", "readwrite")121 .objectStore("reviews");122 reviewsStore.put(newReview);123 // delete review from outbox store124 outboxStore = db125 .transaction("outbox", "readwrite")126 .objectStore("outbox");127 outboxStore.delete(requestId);128 }129 }130 );131 });132 })133 );134});135self.addEventListener("fetch", (event) => {136 const requestUrl = new URL(event.request.url);137 if (requestUrl.origin === location.origin) {138 const restaurantImagePathRegex = /img\/[0-9_\-a-zA-Z]+\.jpg/;139 if (restaurantImagePathRegex.test(requestUrl.pathname)) {140 event.respondWith(serveRestaurantImage(event.request));141 return;142 }143 // cache should match index.html to /144 if (requestUrl.pathname.startsWith("/index.html")) {145 event.respondWith(146 caches.match("/").then((response) => response || fetch(event.request))147 );148 return;149 }150 } else if (requestUrl.origin === "https://api.tiles.mapbox.com") {151 event.respondWith(serveMapboxTiles(event.request));152 return;153 } else if (requestUrl.origin === "https://fonts.gstatic.com") {154 event.respondWith(serveFonts(event.request));155 return;156 } else if (157 requestUrl.origin === "https://use.fontawesome.com" &&158 !requestUrl.pathname.endsWith(".css")159 ) {160 event.respondWith(serveFontAwesome(event.request));161 return;162 }163 event.respondWith(164 caches165 .match(event.request, { ignoreSearch: true }) // ignore search for /restaurant.html?id=X166 .then((response) => response || fetch(event.request))167 );168});169const serveRestaurantImage = (request) => {170 // image urls have multiple - and _ for orientation, crop, pixel density and screen size171 // the relevant part of the url is before the first -172 const storageUrl = request.url.split("-")[0];173 return caches.open(restaurantImagesCache).then((cache) =>174 cache.match(storageUrl).then((response) => {175 if (response) return response;176 return fetch(request)177 .then((networkResponse) => {178 cache.put(storageUrl, networkResponse.clone());179 return networkResponse;180 })181 .catch((error) => {182 console.log(error);183 // use of offline images inspired by Salah Hamza's stage 1 project184 // Available at https://github.com/SalahHamza/mws-restaurant-stage-1/blob/master/sw.js185 if (request.url.includes("wide"))186 return caches.match("/img/offline_wide.svg");187 return caches.match("/img/offline.svg");188 });189 })190 );191};192const serveMapboxTiles = (request) =>193 caches.open(mapboxTilesCache).then((cache) =>194 cache.match(request.url).then((response) => {195 if (response) return response;196 // if request isn't cached, cache it when fetch response is returned197 return fetch(request).then((networkResponse) => {198 cache.put(request.url, networkResponse.clone());199 return networkResponse;200 });201 })202 );203const serveFonts = (request) =>204 caches.open(fontsCache).then((cache) =>205 cache.match(request.url).then((response) => {206 if (response) return response;207 // if request isn't cached, cache it when fetch response is returned208 return fetch(request).then((networkResponse) => {209 cache.put(request.url, networkResponse.clone());210 return networkResponse;211 });212 })213 );214const serveFontAwesome = (request) =>215 caches.open(fontAwesomeCache).then((cache) =>216 cache.match(request.url).then((response) => {217 if (response) return response;218 // if request isn't cached, cache it when fetch response is returned219 return fetch(request).then((networkResponse) => {220 cache.put(request.url, networkResponse.clone());221 return networkResponse;222 });223 })...
storage-buckets.https.any.js
Source:storage-buckets.https.any.js
1// META: title=Buckets API: Tests for indexedDB API.2// META: global=window,worker3// META: script=resources/support-promises.js4promise_test(async testCase => {5 const inboxBucket = await navigator.storageBuckets.open('inbox_bucket');6 testCase.add_cleanup(() => {7 navigator.storageBuckets.delete('inbox_bucket');8 });9 const outboxBucket = await navigator.storageBuckets.open('outbox_bucket');10 testCase.add_cleanup(() => {11 navigator.storageBuckets.delete('outbox_bucket');12 });13 // Set up similar databases in two buckets.14 const inboxDb = await new Promise(resolve => {15 const request = inboxBucket.indexedDB.open('messages');16 request.onupgradeneeded = (event) => {17 const inboxStore =18 event.target.result.createObjectStore('primary', {keyPath: 'id'});19 event.target.transaction.commit();20 };21 request.onsuccess = () => resolve(request.result);22 request.onerror = () => reject(request.error);23 });24 const txn = inboxDb.transaction(['primary'], 'readwrite');25 const inboxStore = txn.objectStore('primary');26 inboxStore.put({ subject: 'Bonjour', id: '42'});27 txn.commit();28 await promiseForTransaction(testCase, txn);29 const outboxDb = await new Promise(resolve => {30 const request = outboxBucket.indexedDB.open('messages');31 request.onupgradeneeded = (event) => {32 const outboxStore =33 event.target.result.createObjectStore('primary', {keyPath: 'id'});34 event.target.transaction.commit();35 };36 request.onsuccess = () => resolve(request.result);37 request.onerror = () => reject(request.error);38 });39 const txn2 = outboxDb.transaction(['primary'], 'readwrite');40 const outboxStore = txn2.objectStore('primary');41 outboxStore.put({ subject: 're: Bonjour', id: '47'});42 txn2.commit();43 await promiseForTransaction(testCase, txn2);44 // Make sure it's possible to read from the bucket database.45 const inboxMessage = await new Promise(resolve => {46 const txn3 = inboxDb.transaction(['primary'], 'readonly');47 const inboxLookup = txn3.objectStore('primary').get('42');48 inboxLookup.onsuccess = (e) => resolve(inboxLookup.result);49 inboxLookup.onerror = (e) => reject(inboxLookup.error);50 });51 assert_equals(inboxMessage.subject, 'Bonjour');52 // Make sure it's possible to read from the other bucket database.53 const outboxMessage = await new Promise(resolve => {54 const txn4 = outboxDb.transaction(['primary'], 'readonly');55 const outboxLookup = txn4.objectStore('primary').get('47');56 outboxLookup.onsuccess = (e) => resolve(outboxLookup.result);57 outboxLookup.onerror = (e) => reject(outboxLookup.error);58 });59 assert_equals(outboxMessage.subject, 're: Bonjour');60 // Make sure they are different databases (looking up the data keyed on `47`61 // fails in the first database).62 const nonexistentInboxMessage = await new Promise(resolve => {63 const txn5 = inboxDb.transaction(['primary'], 'readonly');64 const nonexistentInboxLookup = txn5.objectStore('primary').get('47');65 nonexistentInboxLookup.onsuccess = (e) =>66 resolve(nonexistentInboxLookup.result);67 nonexistentInboxLookup.onerror = (e) =>68 reject(nonexistentInboxLookup.error);69 });70 assert_equals(nonexistentInboxMessage, undefined);...
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const writeFile = promisify(fs.writeFile);6const outbox = require('./outbox.js');7const getOutbox = require('./getOutbox.js');8const { getOutbox: getOutbox2 } = require('./outbox.js');9const { getOutbox: getOutbox3 } = require('./getOutbox.js');10const { getOutbox: getOutbox4 } = require('./outbox.js');11const { getOutbox: getOutbox5 } = require('./outbox.js');12const { getOutbox: getOutbox6 } = require('./outbox.js');13const { getOutbox: getOutbox7 } = require('./outbox.js');14const { getOutbox: getOutbox8 } = require('./outbox.js');15const { getOutbox: getOutbox9 } = require('./outbox.js');16const { getOutbox: getOutbox10 } = require('./outbox.js');17const { getOutbox: getOutbox11 } = require('./outbox.js');18const { getOutbox: getOutbox12 } = require('./outbox.js');19const { getOutbox: getOutbox13 } = require('./outbox.js');20const { getOutbox: getOutbox14 } = require('./outbox.js');21const { getOutbox: getOutbox15 } = require('./outbox.js');22const { getOutbox: getOutbox16 } = require('./outbox.js');23const { getOutbox: getOutbox17 } = require('./outbox.js');24const { getOutbox: getOutbox18 } = require('./outbox.js');25const { getOutbox: getOutbox19 } = require('./outbox.js');26const { getOutbox: getOutbox20 } = require('./outbox.js');27const { getOutbox: getOutbox21 } = require('./outbox.js');28const { getOutbox: getOutbox22 } = require('./outbox.js');29const { getOutbox: getOutbox23 } = require('./outbox.js');30const { getOutbox: getOutbox24 } = require('./outbox.js');31const { getOutbox: getOutbox25 } = require('./outbox.js
Using AI Code Generation
1var wpt = require('wpt-api');2var options = {3};4wpt.outboxStore(options, function (err, data) {5 console.log(data);6});7var wpt = require('wpt-api');8var options = {9};10wpt.outboxStore(options, function (err, data) {11 wpt.outboxRetrieve({testId: data.data.testId}, function (err, data) {12 console.log(data);13 });14});15var wpt = require('wpt-api');16var options = {17};18wpt.outboxStore(options).then(function (data) {19 return wpt.outboxRetrieve({testId: data.data.testId});20}).then(function (data) {21 console.log(data);22}).catch(function (err) {23 console.log(err);24});25var wpt = require('wpt-api');26var options = {27};28async function run() {29 try {30 var data = await wpt.outboxStore(options);
Using AI Code Generation
1var wptb = require("wptb");2var outboxStore = wptb.outboxStore;3var data = {4};5outboxStore("test", data, function (err, data) {6 if (err) {7 console.log("error");8 } else {9 console.log("success");10 }11});12var wptb = require("wptb");13var outboxRemove = wptb.outboxRemove;14outboxRemove("test", function (err, data) {15 if (err) {16 console.log("error");17 } else {18 console.log("success");19 }20});21var wptb = require("wptb");22var outboxList = wptb.outboxList;23outboxList(function (err, data) {24 if (err) {25 console.log("error");26 } else {27 console.log("success");28 }29});30var wptb = require("wptb");31var outboxGet = wptb.outboxGet;32outboxGet("test", function (err, data) {33 if (err) {34 console.log("error");
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var file = fs.createWriteStream('outboxStore.txt');4var page = wptools.page('Barack_Obama');5page.outboxStore(function(err, data){6 if (err) {7 console.log('error', err);8 }9 else {10 console.log('data', data);11 }12});
Using AI Code Generation
1const wptb = require('wptb');2wptb.outboxStore('test', {name: 'test'}).then(function(success){3 console.log(success);4}).catch(function(error){5 console.log(error);6});7const wptb = require('wptb');8wptb.outboxDelete('test').then(function(success){9 console.log(success);10}).catch(function(error){11 console.log(error);12});13const wptb = require('wptb');14wptb.outboxClear('test').then(function(success){15 console.log(success);16}).catch(function(error){17 console.log(error);18});19const wptb = require('wptb');20wptb.outboxGetAll('test').then(function(success){21 console.log(success);22}).catch(function(error){23 console.log(error);24});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!