Commit 95176033 authored by Michał "rysiek" Woźniak's avatar Michał "rysiek" Woźniak 🔒

WIP #64: using 3 gateways and returning first successful result

parent 17c31bcc
Pipeline #46161 passed with stage
in 21 minutes and 53 seconds
......@@ -22,18 +22,58 @@ var gateways = [
'https://ipfs.best-practice.se/ipns/' // Sweden
]
/*
* to do this right we need a Promise.any() polyfill
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any
*/
Promise.any = async (promises) => {
// Promise.all() is the polar opposite of Promise.any()
// in that it returns as soon as there is a first rejection
// but without it, it returns an array of resolved results
return Promise.all(
promises.map(p => {
return new Promise((resolve, reject) =>
// swap reject and resolve, so that we can use Promise.all()
// and get the result we need
Promise.resolve(p).then(reject, resolve)
);
})
// now, swap errors and values back
).then(
err => Promise.reject(err),
val => Promise.resolve(val)
);
};
/**
* getting content using regular HTTP(S) fetch()
*/
let fetchContentFromGatewayIPNS = (url) => {
// we're going to try a random gateway and building an URL of the form:
// https://<gateway_address>/<ipnsPubkey>/<rest_of_URL>
var ipnsUrl = gateways[Math.floor(Math.random() * gateways.length)] + ipnsPubKey + url.replace(/https?:\/\/[^/]+/, '')
var ipnsUrl = ipnsPubKey + url.replace(/https?:\/\/[^/]+/, '')
// pick 3 gateways, at random
var useGateways = new Array()
while (useGateways.length < 3) {
// put in the address while we're at it
useGateways.push(
gateways
.splice(Math.floor(Math.random() * gateways.length), 1)[0] + ipnsUrl
)
}
console.log(`Samizdat: gateway IPNS:\n+-- fetching: ${ipnsUrl}`)
// debug log
console.log(`Samizdat: gateway IPNS fetching:\n ${useGateways.join('\n ')}`)
return fetch(ipnsUrl, {cache: "reload"})
return Promise.any(
useGateways.map(
u=>fetch(u, {cache: "reload"})
))
.then((response) => {
// 4xx? 5xx? that's a paddlin'
if (response.status >= 400) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment