Upgrade js-ipfs version and add support for 404 pages.
This commit is contained in:
parent
aba3b8d8b4
commit
5624a03168
|
@ -17,6 +17,6 @@
|
|||
"webpack-dev-server": "^2.4.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"ipfs": "0.27.1"
|
||||
"ipfs": "0.27.5"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -40,6 +40,22 @@ function initialize_ipfs() {
|
|||
|
||||
let ipfs_initialized
|
||||
|
||||
function response(status_code, status_text, body, headers={}) {
|
||||
// Return a promise for a response with the given HTTP status code, status text, and HTML body.
|
||||
return new Promise((resolve, reject) => {
|
||||
resolve(
|
||||
new Response(
|
||||
body,
|
||||
{
|
||||
status: status_code,
|
||||
statusText: status_text,
|
||||
headers: headers
|
||||
}
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
if (!event.request.url.startsWith(self.location.origin + '/ipfs')) {
|
||||
return console.log('Fetch not in scope:', event.request.url)
|
||||
|
@ -47,27 +63,25 @@ self.addEventListener('fetch', (event) => {
|
|||
|
||||
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() {
|
||||
ipfs_initialized.then(() => {
|
||||
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)
|
||||
})
|
||||
}).then((contents_buffer) => {
|
||||
return response(200, 'OK', contents_buffer)
|
||||
}).catch((error) => {
|
||||
console.log(error)
|
||||
return response(
|
||||
404, 'Not Found',
|
||||
Buffer.from('<html><head><title>404 Not Found</title></head><body bgcolor="white"><center><h1>404 Not Found</h1></center><hr><center>Intergalactic</center></body></html>'),
|
||||
{'Content-Type': 'text/html; charset=utf-8'}
|
||||
)
|
||||
})
|
||||
)
|
||||
})
|
||||
|
|
Reference in New Issue