{ // 3 persistTask(event.data.data); // 4 registration.sync.register('task-sync'); // 5 }; let db = null; // 6 let request = indexedDB.open("TaskDB", 1); // 7 request.onupgradeneeded = function(event) { // 8 db = event.target.result; // 9 if […]" /> { // 3 persistTask(event.data.data); // 4 registration.sync.register('task-sync'); // 5 }; let db = null; // 6 let request = indexedDB.open("TaskDB", 1); // 7 request.onupgradeneeded = function(event) { // 8 db = event.target.result; // 9 if […]"> Progressive web app essentials: Service worker background sync - bbdiversinfo
Connect with us

Société

Progressive web app essentials: Service worker background sync

Published

on

Spread the love


const URL = "https://8014-35-223-70-178.ngrok-free.app/"; // 1
const taskChannel = new BroadcastChannel('task-channel'); // 2
taskChannel.onmessage = event => { // 3
  persistTask(event.data.data); // 4
  registration.sync.register('task-sync'); // 5
};

let db = null; // 6
let request = indexedDB.open("TaskDB", 1); // 7
request.onupgradeneeded = function(event) { // 8
  db = event.target.result; // 9
  if (!db.objectStoreNames.contains("tasks")) { // 10
    let tasksObjectStore = db.createObjectStore("tasks", { autoIncrement: true }); // 11
  }
};
request.onsuccess = function(event) { db = event.target.result; }; // 12
request.onerror = function(event) { console.log("Error in db: " + event); }; // 13

persistTask = function(task){ // 14
  let transaction = db.transaction("tasks", "readwrite");
  let tasksObjectStore = transaction.objectStore("tasks");
  let addRequest = tasksObjectStore.add(task);
  addRequest.onsuccess = function(event){ console.log("Task added to DB"); };
  addRequest.onerror = function(event) { console.log(“Error: “ + event); };
}
self.addEventListener('sync', async function(event) { // 15
  if (event.tag == 'task-sync') {
    event.waitUntil(new Promise((res, rej) => { // 16
      let transaction = db.transaction("tasks", "readwrite");
      let tasksObjectStore = transaction.objectStore("tasks");
      let cursorRequest = tasksObjectStore.openCursor();
      cursorRequest.onsuccess = function(event) { // 17
        let cursor = event.target.result;
        if (cursor) {
          let task = cursor.value; // 18
          fetch(URL + 'todos/add', // a
            { method: 'POST', 
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ "task" : task }) 
            }).then((serverResponse) => {
              console.log("Task saved to backend.");
              deleteTasks(); // b
              res(); // b
            }).catch((err) => {
              console.log("ERROR: " + err);
              rej(); //c
            })
          }
        } 
    }))
  }
})
async function deleteTasks() { // 19
  const transaction = db.transaction("tasks", "readwrite");
  const tasksObjectStore = transaction.objectStore("tasks");
  tasksObjectStore.clear();
  await transaction.complete;
}

Now let’s talk about what is happening in this code.

  1. We need to route our requests through the same secure tunnel we created with ngrok, so we save the URL here.
  2. Create the broadcast channel with the same name so we can listen for messages.
  3. Here, we are watching for task-channel message events. In responding to these events, we do two things:
  4. Call persistTask() to save the new task to IndexedDB.
  5. Register a new sync event. This is what invokes the special capability for retrying requests intelligently. The sync handler allows us to specify a promise that it will retry when the network is available, and implements a back off strategy and give-up conditions.
  6. With that done, we create a reference for our database object.
  7. Obtain a “request” for the handle on our database. Everything on IndexedDB is handled asynchronously. (For an excellent overview of IndexedDB, I recommend this series.)
  8. The onupgradeneeded event fires if we are accessing a new or up-versioned database. 
  9. Inside onupgradeneeded, we get a handle on the database itself, with our global db object.
  10. If the tasks collection is not present, we create the tasks collection.
  11. If the database was successfully created, we save it to our db object.
  12. Log the error if the database creation failed.
  13. The persistTask() function called by the add-task broadcast event (4). This simply puts the new task value in the tasks collection.
  14. Our sync event. This is called by the broadcast event (5). We check for the event.tag field being task-sync so we know it’s our task-syncing event.
  15. event.waitUntil() allows us to tell the serviceWorker that we are not done until the Promise inside it completes. Because we are in a sync event, this has special meaning. In particular, if our Promise fails, the syncing algorithm will keep trying. Also, remember that if the network is unavailable, it will wait until it becomes available.
    1. We define a new Promise, and within it we begin by opening a connection to the database.
  16. Within the database onsuccess callback, we obtain a cursor and use it to grab the task we saved. (We are leveraging our wrapping Promise to deal with nested asynchronous calls.)
  17. Now we have a variable with the value of our broadcast task in it. With that in hand:
    1. We issue a new fetch request to our expressJS /todos/add endpoint.
    2. Notice that if the request succeeds, we delete the task from the database and call res() to resolve our outer promise.
    3. If the request fails, we call rej(). This will reject the containing promise, letting the Sync API know the request must be retried.
  18. The deleteTasks() helper method deletes all the tasks in the database. (This is a simplified example that assumes one tasks creation at a time.)

Clearly, there is a lot to this, but the reward is being able to effortlessly retry requests in the background whenever our network is spotty. Remember, we are getting this in the browser, across all kinds of devices, mobile and otherwise.

Testing the PWA example

If you run the PWA now and create a to-do, it’ll be sent to the back end and saved. The interesting test is to open devtools (F12) and disable the network. You can find the “Offline” option in the “throttling” menu of the network tab like so:

Advertisement
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Société

Messy data is holding enterprises back from AI

Published

on

Spread the love

Overall, the report underscores that although enterprises are eager to harness the potential of generative AI, significant infrastructure and data management groundwork is required to realize its benefits and ensure sustainable, long-term success.

A CIO’s to-do list from hell

Most enterprises knew they had data issues long before AI started to impact the market in significant ways. Indeed, most have avoided AI and business intelligence investments due to their lack of confidence in their data. Nobody in the company completely understands where the data is and what it means. Silo leaders own and manage the data, so there is no single source of truth for things as simple as what a customer is and where customer data should come from. Redundancy is common in sales, production tracking, and other areas where the data is mismanaged.

How did things get this bad? Most enterprises spent years focused on new, shiny objects such as ERP and CRM systems, which contain important data, but it’s locked up in proprietary data stores. After ERP and CRM came data warehousing, distributed systems, data integration, and now cloud. Through it all, data has gotten more complex, distributed, and heterogeneous, with a lack of centralized control. Too many companies don’t understand the metadata and can’t trace data properly through the business processes. Also, acquisitions have driven some data redundancy; many enterprises still operate the older systems that came with the businesses they acquired. Now, we’re facing AI, where the meaning, structure, and truthfulness of data are not optional.

Continue Reading

Société

Developer productivity poorly understood, report says

Published

on

Spread the love

Developer productivity is neither well-understood nor enabled, according to Atlassian’s just-released State of Developer Experience Report 2024. The report also found that interest in the developer experience, or DX, is growing but efforts are lagging.

Announced July 15 and accessible at atlassian.com, the State of Developer Experience Report 2024 is based on a survey of 1,250 engineering leaders in the US, Germany, France, and Australia, and 900 developers around the world. The survey was intended to find out what practices keep software development work flowing smoothly and what practices introduce friction. Feelings about work environments in the age of generative AI and microservices also were assessed. Among the findings were that less than half of developers believe their organizations prioritize developer experience and two out of three developers lose more than eight hours a week due to inefficiencies in their roles. Also, two out of three developers are not seeing significant productivity gains from using AI tools yet.

The top five contributors to developer role complexity, according to engineering leaders, include understaffing, expansion of the developer role, new technology, switching context between tools, and collaboration with other teams. The top five contributors to developer time loss cited include technical debt, insufficient documentation, build processes, lack of time for deep work, and lack of clear direction. Almost all engineering leaders surveyed, 99%, acknowledge that the developer role has become more complex. The top five practices leaders believe will improve developer productivity and satisfaction include AI automation, provision of new collaboration tools, risk taking and experimentation, streamlining decision-making, and hosting hackathons.

Continue Reading

Société

Talk of GitLab sale highlights growing importance of DevSecOps platforms

Published

on

Spread the love

By connecting these two capabilities, he said, development teams can release and monitor their applications with a single platform. “Whether that makes sense from a business perspective is a matter for those two companies to decide, but most definitely, enterprise platform teams are linking those capabilities together on their own.”

Platform compatibility

John Annand, research practice lead at Info-Tech Research Group, also thinks that, if a Datadog deal occurred, it could be a good match.

“GitLab is a very popular DevSecOps tool that lets enterprises optimize their pre-production activities rather than having to build their own CI/CD and testing pipelines from multiple vendors’ products and from scratch,” he said in an email. “Datadog’s product is all the information about how a deployed application behaves once it’s left the dev environment and is forced to deal with real-world conditions.”

Continue Reading

Société

How to use HybridCache in ASP.NET Core

Published

on

Spread the love

The key benefits of HybridCache are greater simplicity, improved performance, and enhanced efficiency.

HybridCache is an abstract class pertaining to the Microsoft.Extensions.Caching.Hybrid namespace. To store data to the cache and retrieve data from the cache, you use the GetOrCreateAsync method of the HybridCache class. This method takes advantage of the cache key to retrieve an object from the primary cache.

Now, if the object requested by the application is not available in the cache, i.e., in the case of a cache miss, the method checks the secondary cache if it is configured. If the data is not available there, the method stores the object in both the primary and secondary caches.

Continue Reading

Société

Building next-generation applications with the Windows Application SDK

Published

on

Spread the love

Download channels show upcoming features

The Windows App SDK is available in three different channels; you can choose between the current stable release, a preview release for features that should ship soon, or an experimental channel where new features are trialed. The current supported release is Version 1.5.5, released early in July 2024. The next major release will be in six months or so. The current preview release predates the current build, so a new version should be available soon. Experimental builds are based on the development tree of the planned 1.6 release, with a second release in July 2024.

Microsoft provides a list of the features available in each channel, along with the current support life cycle. Versions are supported for a year from initial release, so the current 1.5 release will be in support until the end of February 2025, with Version 1.4 dropping out of support at the end of August 2024. There’s one unusual caveat to the Windows App SDK support: Although it offers compatibility back to Windows 10 Version 1809, technically only in-support versions of Windows are covered.

The Windows App SDK and the Copilot Runtime

The Windows App SDK is intended to be a key component of the Copilot Runtime, hosting, among other features, artificial intelligence APIs based on the Phi Silica local generative AI model and AI-powered OCR services. However, these promised features are still missing from the current Version 1.6 experimental builds, two months after Build. If Microsoft wants to shift developers’ attention to Windows, it needs to capitalize on the capabilities of its new hardware and ship Copilot Runtime APIs as soon as possible and accelerate the transition of Version 1.6 from experimental to production.

Continue Reading

Société

Google’s Genkit for Go brings AI app development to Go language

Published

on

Spread the love

Google has unveiled Genkit for Go, an open-source framework for building AI-powered applications and cloud services natively in Go. The project is a collaboration between Google’s Firebase and Go language teams.

Introduced July 17 and currently in an alpha state, Genkit for Go enables developers to build generative AI applications by combining Go’s performance and concurrency advantages with Genkit’s libraries and tools. Potential use cases include intelligent assistants that understand complex requests, customer support agents using retrieval-augmented generation (RAG), and data transformation tools that convert unstructured data such as natural language into structured formats (SQL, queries, tables) for deeper analysis.

A guide to getting started with Genkit for Go can be found at firebase.google.com. Genkit for Go follows the May introduction of Firebase Genkit for Node.js, for JavaScript and TypeScript developers. Genkit provides lightweight, composable abstractions to simplify development of sophisticated AI workflows without sacrificing control and customizability, Google said. The framework features:

Continue Reading

Société

Google rolls out new dev tools focusing on open source and GenAI

Published

on

Spread the love

IDC’s Dayaratna said he was particularly intrigued by Project Vanni because it directly addresses a particularly difficult coding obstacle, especially when development teams exist in many different countries speaking many different languages. The problem can also exist in countries with many different local languages, such as when widespread Indian teams have speakers writing in, for example, Hindi, Bengali, Marathi and Kannada.

The Vanni project is dealing with two difficult challenges. One is translating coding references without missing key technical details, especially when it is being translated into multiple languages. The second, potentially more severe, problem is doing these translations within a GenAI environment, where the algorithm can hallucinate or even simply try to extrapolate meaning where it might predict the next word incorrectly. If that happens, the translations become confusing and possibly destructive.

“What (coders) need is translation that is contextual and is specific to natural language prompts in software,” Dayaratna said, adding that translation specialized for developers “does not exist” yet. 

Continue Reading

Société

Deno adds workspaces for managing monorepos

Published

on

Spread the love

The latest update to the Deno TypeScript /JavaScript and WebAssembly runtime features workspace support along with Node.js compatibility improvements.

Deno 1.45 was introduced July 11. The release introduces workspaces for managing monorepos, simplifying dependency management, configuration sharing, and module organization across large code bases, Deno Land said. There are two forms of supported workspaces: Deno-first workspaces defined in deno.json and backwards-compatible NPM workspaces. Global configuration for these workspaces is applied to each member package but can be overridden by members. Developers can mix and match NPM and Deno workspaces, with an NPM package inside a Deno workspace or vice versa.

For Node.js compatibility, Node-API support has been revamped, fixing issues with packages such as prisma, sqlite3,  and  paper. Other Node.js compatibility improvements include working on support for dd.trace and support for fs.lutimes and fs.lutimesSync. Also, node:crypto and node:zlib were added. The node:http module was updated, with capabilities such as Server#close() now doing a graceful shutdown, allowing in-flight requests to finish. In another improvement, the node:vm will consume less memory. For NPM support, types shipped with the package are now preferred over types from @types scope.

Continue Reading

Société

Salesforce previews Einstein-powered service agent

Published

on

Spread the love

In order to create an Einstein Service Agent customized for an enterprise, its developers need to access the Einstein 1 platform, start creating a new copilot by giving its specific name and purpose, and then expose it to service topics, Nichols explained, adding that once the service topics are mapped and a LLM is selected, developers can assign knowledge-based actions to the agent.

These knowledge-based actions, according to the company, make the agent autonomous or allow the agent or chatbot to take actions without having a human in the loop, differentiating it from regular programmed chatbots or service agents.

One of the main differences between an older predictive chatbot and the Einstein Service Agent is its ability to understand intent because of its LLM base, said Keith Kirkpatrick, research director at The Futurum Group.

Continue Reading

Société

Mistral’s new Codestral Mamba to aid longer code generation

Published

on

Spread the love

The company tested Codestral Mamba on in-context retrieval capabilities up to 256k tokens — twice the number seen in OpenAI’s GPT4o — and found its 7B version performing better than open source models in several benchmarking tests, such as HumanEval, MBPP, Spider, and CruxE.

The larger 22B parameter version of the new model also performed significantly better than CodeLlama-34B with the exception of the CruxE benchmark.

While the 7B version is available under the Apache 2.0 license, the larger 22B version is available under a commercial license for self-deployment or community license for testing purposes.

Continue Reading
Advertisement

Derniers Articles

Sports8 mins ago

Como: Cesc Fabregas becomes head coach of Serie A side

Spread the love Cesc Fabregas has become the head coach of Serie A club Como, having previously worked as their...

International10 mins ago

How millions of Americans could go without a paycheck this month due to global Crowdstrike crash – are YOU at risk?

Spread the love By Nikki Main Science Reporter For Dailymail.Com Published: 21:27 BST, 19 July 2024 | Updated: 21:36 BST,...

France14 mins ago

Vittel, Contrex, Hépar… Les eaux minérales ont été traitées par des produits interdits depuis 15 ans, dénonce un rapport : Femme Actuelle Le MAG

Spread the love Nous avons un cadeau pour vous Créez un compte et inscrivez-vous à la newsletter Femme Actuelle pour...

France17 mins ago

le PS veut un vote avant mardi

Spread the love Alors que la gauche peine à s’accorder sur le nom final à proposer au nom du Nouveau...

Santé29 mins ago

À l’Assemblée nationale, l’élection des vice-présidents commence par un couac et doit être refaite

Spread the love La lecture de ce contenu est susceptible d’entraîner un dépôt de cookies de la part de l’opérateur...

Afrique31 mins ago

Cherté de la vie au Sénégal : Bassirou Diomaye Faye veut réduire le prix du loyer

Spread the love En conseil des ministres ce jeudi 18 juillet 2024, le président sénégalais Bassirou Diomaye Faye a évoqué...

France39 mins ago

Seine-Saint-Denis : deux morts par balles dans un probable règlement de comptes

Spread the love Deux personnes ont été tuées par balles et une troisième a été grièvement blessée vendredi soir dans...

France56 mins ago

Libre antenne – TDHA, Sarah a émis des chèques sans provision sur le compte de ses parents décédés

Spread the love Vous pouvez vous abonner au téléchargement périodique d’un fichier audio. Vous pouvez conserver l’émission ainsi téléchargée sur...

International59 mins ago

Tunisia’s President Saied says will seek re-election amid intensified ‘crackdown on opposition’

Spread the loveTunisia’s President Kais Saied said Friday he will stand for re-election in an October vote. The announcement comes...

Afrique1 hour ago

SNH : Le Conseil d’Administration reprogrammé pour le 24 Juillet 2024

Spread the love   Le communiqué ne précise pas les motifs de ce report. Toutefois, cette session était très attendue,...

Sports1 hour ago

Football gossip: Antony, Roberto, Sarr, Madueke, Huijsen, Gruda

Spread the love Leicester have made an improved £21m bid for Juventus winger Matias Soule, 21, and hope to wrap...

International1 hour ago

Praxis considering takeover of shopping centre owner Capital & Regional

Spread the love By Emily Hawkins Updated: 21:50 BST, 19 July 2024 Property investment group Praxis is considering a takeover...

Santé1 hour ago

Le Filip est revenue pour nous sur les addictions, l’homophobie et la politique

Spread the love © Jean RANOBRAC – FTV Le Filip, grande finaliste de la saison 3 de « Drag Race France ». ©...

France1 hour ago

“Il n’y a pas d’équilibre parfait” : Nina Métayer se confie sur sa capacité à mêler vie de famille et obligations professionnelles : Femme Actuelle Le MAG

Spread the love Nous avons un cadeau pour vous Créez un compte et inscrivez-vous à la newsletter Femme Actuelle pour...

France1 hour ago

Des canettes de soda explosent en plein vol et blessent des stewards

Spread the love Des canettes de soda ont explosé à bord de vols de la compagnie aérienne américaine Southwest Airlines....

Afrique2 hours ago

Insolite: des amoureux font un pacte de sang pour préserver leur relation

Spread the love Fabrice AGBLEMAGNON 3 heures . A la Une, People Dans une démonstration d’amour sincère et peu conventionnelle,...

France2 hours ago

Mali : décès du musicien Toumani Diabaté, un « maître de la kora »

Spread the love Le musicien malien Toumani Diabaté, surnommé « roi de la kora », un instrument de musique africain, est décédé...

France2 hours ago

les Bleuets échouent dans leur quête d’un quatrième titre consécutif

Spread the love L’équipe de France des moins de 20 ans, triple championne du monde en titre, a perdu son...

Actualités2 hours ago

Access Denied

Spread the love Access Denied You don’t have permission to access “http://information.tv5monde.com/international/lassemblee-elit-ses-vice-presidents-apres-un-vote-chaotique-lhemicycle-senflamme-deja” on this server. Reference #18.2a3e2217.1721424907.135c30db https://errors.edgesuite.net/18.2a3e2217.1721424907.135c30db

International2 hours ago

French lawmakers cry foul after suspected ballot-stuffing in National Assembly

Spread the loveFrench lawmakers called for an investigation on Friday amid suspicions of ballot-stuffing in a vote for deputy speakers...

Advertisement

Trending