1/** 2 * Copyright (c) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you 5 * may not use this file except in compliance with the License. You may 6 * obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 * implied. See the License for the specific language governing 14 * permissions and limitations under the License. 15 */ 16 17'use strict'; 18 19const CACHE_NAME = 'travis-cache'; 20const JOBS_URL = 'https://api.travis-ci.org/jobs/'; 21 22async function FetchAndCacheIfJob(event) { 23 if (!event.request.url.startsWith(JOBS_URL)) { 24 return fetch(event.request); 25 } 26 27 // Try and retrieve from the cache. 28 const cachedResponse = await caches.match(event.request); 29 if (cachedResponse) { 30 return cachedResponse; 31 } 32 33 // If network request failed just return the response. 34 const response = await fetch(event.request); 35 if (!response || response.status !== 200) { 36 return response; 37 } 38 39 // Extract the JSON from the response. 40 const json = await response.clone().json(); 41 if (json.state !== 'cancelled' && json.state !== 'finished') { 42 return response; 43 } 44 45 var responseToCache = response.clone(); 46 caches.open(CACHE_NAME) 47 .then(cache => { 48 cache.put(event.request, responseToCache); 49 }); 50 51 return response; 52} 53 54self.addEventListener('fetch', event => { 55 event.respondWith(FetchAndCacheIfJob(event)); 56}); 57