Skip to content

Instantly share code, notes, and snippets.

@divyasonaraa
Last active November 28, 2023 09:57
Show Gist options
  • Save divyasonaraa/893f40056d7bce9952f8f6c079deffdb to your computer and use it in GitHub Desktop.
Save divyasonaraa/893f40056d7bce9952f8f6c079deffdb to your computer and use it in GitHub Desktop.
import { Queue } from "workbox-background-sync";
let backgroundSync = "sync" in self.registration ? true : false;
/*
queue- create post
*/
let createBlogQueue = null;
if (backgroundSync) {
createBlogQueue = new Queue("createBlogQueue", {
onSync: async ({ queue }) => {
console.log("queue", queue);
let entry;
while ((entry = await queue.shiftRequest())) {
try {
await fetch(entry.request);
console.log("Replay successful for request", entry.request);
const channel = new BroadcastChannel("sw-messages");
channel.postMessage({ msg: "offline-post-uploaded" });
} catch (error) {
console.error("Replay failed for request", entry.request, error);
// Put the entry back in the queue and re-throw the error:
await queue.unshiftRequest(entry);
throw error;
}
}
},
});
}
/*
events - fetch
*/
if (backgroundSync) {
self.addEventListener("fetch", (event) => {
if (event.request.method == "POST") {
// Clone the request to ensure it's safe to read when
// adding to the Queue.
if (!self.navigator.onLine) {
const promiseChain = fetch(event.request.clone()).catch((err) => {
return createBlogQueue.pushRequest({ request: event.request });
});
event.waitUntil(promiseChain);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment