Adding missing service worker source file.
This commit is contained in:
parent
acc7964f0e
commit
fad1d327f4
|
@ -0,0 +1,74 @@
|
|||
// Forked from https://github.com/ipfs/ipfs-service-worker which does not work with recent versions
|
||||
// of js-ipfs.
|
||||
|
||||
/* global self, Response */
|
||||
|
||||
'use strict'
|
||||
|
||||
const IPFS = require('ipfs')
|
||||
let node
|
||||
|
||||
// https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68
|
||||
self.skipWaiting()
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('install step')
|
||||
|
||||
event.waitUntil(self.skipWaiting())
|
||||
})
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('activate step')
|
||||
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
function initialize_ipfs() {
|
||||
return new Promise((resolve, reject) => {
|
||||
node = new IPFS()
|
||||
|
||||
node.on('ready', () => {
|
||||
console.log('js-ipfs node is ready')
|
||||
resolve()
|
||||
})
|
||||
node.on('error', (err) => {
|
||||
console.log('js-ipfs node errored', err)
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
let ipfs_initialized
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
if (!event.request.url.startsWith(self.location.origin + '/ipfs')) {
|
||||
return console.log('Fetch not in scope:', event.request.url)
|
||||
}
|
||||
|
||||
console.log('Handling fetch event:', event.request.url)
|
||||
|
||||
const headers = {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {}
|
||||
}
|
||||
|
||||
if (!ipfs_initialized) {
|
||||
ipfs_initialized = initialize_ipfs()
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
ipfs_initialized.then(function() {
|
||||
const url = new URL(event.request.url)
|
||||
const multihash = url.pathname
|
||||
return node.files.cat(multihash)
|
||||
}).then(function (contents_buffer) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const response = new Response(contents_buffer, headers)
|
||||
|
||||
resolve(response)
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
|
Reference in New Issue