merkle-btree
Version:
Content-addressed b-tree
87 lines (75 loc) • 2.63 kB
JavaScript
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var isNode = false;
try {
isNode = Object.prototype.toString.call(global.process) === "[object process]";
} catch (e) {
null;
}
function browserGet(url) {
return new Promise(function (resolve, reject) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status >= 200 && xmlHttp.status < 300) resolve(xmlHttp.responseText);else reject(xmlHttp.responseText);
}
};
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
});
}
// thanks https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
function nodeGet(url) {
// return new pending promise
return new Promise(function (resolve, reject) {
// select http or https module, depending on reqested url
var lib = url.startsWith("https") ? require("https") : require("http");
var request = lib.get(url, function (response) {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error("Failed to load page, status code: " + response.statusCode));
}
// temporary data holder
var body = [];
// on every content chunk, push it to the data array
response.on("data", function (chunk) {
return body.push(chunk);
});
// we are done, resolve promise with those joined chunks
response.on("end", function () {
return resolve(body.join(""));
});
});
// handle connection errors of the request
request.on("error", function (err) {
return reject(err);
});
});
}
function getContent(url) {
if (isNode && require.resolve("http") && require.resolve("https")) {
return nodeGet(url);
} else {
return browserGet(url);
}
}
var IPFSGatewayStorage = function () {
function IPFSGatewayStorage() {
var apiRoot = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
_classCallCheck(this, IPFSGatewayStorage);
this.apiRoot = apiRoot;
}
IPFSGatewayStorage.prototype.get = function get(key) {
if (!key.match(/^\/ip(fs|ns)\//)) {
key = "/ipfs/" + key;
}
return getContent(this.apiRoot + key);
};
IPFSGatewayStorage.prototype.remove = function remove() {
return Promise.resolve();
};
IPFSGatewayStorage.prototype.put = function put() {
return Promise.resolve();
};
return IPFSGatewayStorage;
}();
export default IPFSGatewayStorage;