React uygulamasını service worker ile güncelleyebileceğimiz bir kod örneği paylaşabilir misiniz?
sizin için yapay zeka'ya bir örnek hazırlattım
// public/sw.js - Service Worker dosyası
const CACHE_VERSION = 'v1.0.0';
const CACHE_NAME = `app-cache-${CACHE_VERSION}`;
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/main.js',
'/main.css'
]);
}).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
}).then(() => self.clients.claim())
.then(() => {
return self.clients.matchAll().then(clients => {
return clients.map(client => {
return client.postMessage({
type: 'UPDATE_AVAILABLE',
version: CACHE_VERSION
});
});
});
})
);
});
self.addEventListener('fetch', (event) => {
if (event.request.url.includes('/api/')) {
return;
}
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request).then((networkResponse) => {
if (networkResponse && networkResponse.status === 200 && event.request.method === 'GET') {
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
}
return networkResponse;
});
})
);
});
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// src/serviceWorker.js - Service Worker Kayıt ve Kontrol
export function register() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
registration.addEventListener('updatefound', () => {
const installingWorker = registration.installing;
installingWorker.addEventListener('statechange', () => {
if (installingWorker.state === 'installed' && navigator.serviceWorker.controller) {
const event = new CustomEvent('onUpdateAvailable');
window.dispatchEvent(event);
}
});
});
});
navigator.serviceWorker.addEventListener('message', event => {
if (event.data && event.data.type === 'UPDATE_AVAILABLE') {
const updateEvent = new CustomEvent('onUpdateAvailable');
window.dispatchEvent(updateEvent);
}
});
});
}
}
export function checkForUpdates() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.update();
});
}
}
export function applyUpdate() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
if (registration.waiting) {
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
}
});
let refreshing = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (!refreshing) {
refreshing = true;
window.location.reload(true);
}
});
}
}
// src/App.jsx - React Uygulama Kodu
import React, { useEffect, useState } from 'react';
import { register, checkForUpdates, applyUpdate } from './serviceWorker';
function App() {
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
useEffect(() => {
register();
const handleUpdateAvailable = () => {
setShowUpdateBanner(true);
};
window.addEventListener('onUpdateAvailable', handleUpdateAvailable);
return () => {
window.removeEventListener('onUpdateAvailable', handleUpdateAvailable);
};
}, []);
const handleUpdate = () => {
applyUpdate();
};
return (
<div className="app">
<h1>Uygulama İçeriği</h1>
{showUpdateBanner && (
<div className="update-banner">
<p>Yeni bir güncelleme mevcut!</p>
<button onClick={handleUpdate}>Şimdi Güncelle</button>
<button onClick={() => setShowUpdateBanner(false)}>Daha Sonra</button>
</div>
)}
<button onClick={checkForUpdates}>Güncellemeleri Kontrol Et</button>
</div>
);
}
export default App;
// Backend tarafında deploy-update.php - Frontend dosyalarını güncelleyen API
// <?php
// header('Content-Type: application/json');
//
// $newVersion = "1.0.1";
// $updateSuccess = false;
//
// try {
// $updatePackage = "https://sizin-sunucunuz.com/updates/frontend-{$newVersion}.zip";
// $tempPath = "../temp/update.zip";
//
// file_put_contents($tempPath, file_get_contents($updatePackage));
//
// $zip = new ZipArchive;
// if ($zip->open($tempPath) === TRUE) {
// $zip->extractTo("../public/");
// $zip->close();
//
// file_put_contents("../public/version.json", json_encode([
// "version" => $newVersion,
// "buildDate" => date("Y-m-d H:i:s")
// ]));
//
// $updateSuccess = true;
// }
//
// echo json_encode([
// "success" => $updateSuccess,
// "version" => $newVersion
// ]);
// } catch (Exception $e) {
// echo json_encode([
// "success" => false,
// "error" => $e->getMessage()
// ]);
// }
// ?> Temel Çalışma Mantığı
- Service Worker Kaydı: Uygulama yüklendiğinde Service Worker kayıt edilir
- Önbelleğe Alma: Service Worker uygulama dosyalarını önbelleğe alır
- Güncelleme Kontrolü:
- Manuel olarak "Güncellemeleri Kontrol Et" butonuyla
- Veya her sayfa yenilenmesinde otomatik olarak
- Yeni Sürüm Algılama: Service Worker yeni bir sürüm algıladığında kullanıcıya bildirim gösterir
- Güncelleme Uygulama: Kullanıcı "Şimdi Güncelle" dediğinde yeni Service Worker aktifleşir ve sayfa yenilenir
- Sunucu Tarafı: PHP tarafında yeni frontend dosyaları sunucuya yüklenir ve Service Worker bunları algılar
Bu şekilde uygulama, sunucu yeniden başlatılmadan veya kullanıcı zorla sayfayı yenilemeden güncelleştirilir.