{"size": 1653, "ext": "js", "max_stars_repo_path": "stale-while-revalidate/sw.js", "max_stars_repo_name": "ms-fadaei/service-worker", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stale-while-revalidate/sw.js", "max_issues_repo_name": "ms-fadaei/service-worker", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stale-while-revalidate/sw.js", "max_forks_repo_name": "ms-fadaei/service-worker", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.5178571429, "max_line_length": 88, "alphanum_fraction": 0.5868118572}
const NETWORK_TIMEOUT = 100;
const CACHE_VERSION = 1;
const CASH_NAME = `swr-${CACHE_VERSION}`;
const IMAGE_REPO_LIST = [
    "../assets/images/img-1.jpeg",
];

self.addEventListener("install", function (event) {
    event.waitUntil(precache());
    event.waitUntil(self.skipWaiting());
});

self.addEventListener("fetch", function (event) {
    console.log("Request to:", event.request.url);

    event.respondWith(fromCache(event.request).catch(() => fetch(event.request)));
    event.waitUntil(stealWhileRevalidate(event.request));
})

function precache() {
    return caches.open(CASH_NAME)
        .then(res => res.addAll(IMAGE_REPO_LIST))
        .catch(err => console.error("An error occurred on precaching!", err));
}

function fromCache(request) {
    return caches.open(CASH_NAME)
        .then(function (cache) {
            return cache.match(request)
                .then(function (response) {
                    if (!response) return Promise.reject("no-cache");

                    console.log(`Response for the "${request.url}" served from cache!`);
                    return response;
                });
        })
}

let i = 1;

function stealWhileRevalidate(request) {
    if (request.url.includes("/assets/images/img-")) {
        var url = `../assets/images/img-${i++ % 5 + 1}.jpeg`;
    } else {
        return Promise.resolve();
    }

    return fetch(url)
        .then(function (response) {
            return caches.open(CASH_NAME)
                .then(cache => {
                    console.log("Cache revalidated", request.url);
                    return cache.put(request, response);
                });
        });
}