This repository has been archived by the owner on Mar 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathipfshost.js
66 lines (54 loc) · 1.64 KB
/
ipfshost.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var IPFS = require("ipfs-mini");
var request = require("request");
var Readable = require('stream').Readable;
var URL = require("url");
var fs = require("fs");
function IPFSHost(host, port, protocol) {
this.host = host || "localhost";
this.port = port || 5001;
this.protocol = protocol || "http";
this.ipfs = new IPFS({
host: this.host,
port: this.port,
protocol: this.protocol
});
}
IPFSHost.prototype.putContents = function(contents) {
var self = this;
return new Promise(function(accept, reject) {
self.ipfs.add(contents, (err, result) => {
if (err) return reject(err);
accept("ipfs://" + result);
});
});
}
IPFSHost.prototype.putFile = function(file) {
var self = this;
return new Promise(function(accept, reject) {
fs.readFile(file, "utf8", function(err, data) {
if (err) return reject(err);
self.putContents(data).then(accept).catch(reject);
});
});
};
IPFSHost.prototype.get = function(uri) {
var self = this;
return new Promise(function(accept, reject) {
if (uri.indexOf("ipfs://") != 0) {
return reject(new Error("Don't know how to resolve URI " + uri));
}
var hash = uri.replace("ipfs://", "");
var path = 'api/v0/cat/' + hash;
var processedUrl = `${self.protocol}://${self.host}:${self.port}/${path}`;
request(processedUrl, function(error, response, body) {
if(error) {
reject(error);
} else if (response.statusCode !== 200) {
reject(new Error(`Unknown server response ${response.statusCode} when downloading hash ${hash}`));
} else {
accept(body);
};
});
});
};
module.exports = IPFSHost;