diff --git a/package.json b/package.json index d182772..abda72d 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,6 @@ "webpack-dev-server": "^2.4.5" }, "dependencies": { - "ipfs": "0.27.1" + "ipfs": "0.27.5" } } diff --git a/src/fetcher.js b/src/fetcher.js index 7494320..492e839 100644 --- a/src/fetcher.js +++ b/src/fetcher.js @@ -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('404 Not Found

404 Not Found


Intergalactic
'), + {'Content-Type': 'text/html; charset=utf-8'} + ) }) ) })