-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
95 lines (81 loc) · 2.55 KB
/
server.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var express = require('express');
var ipfsAPI = require('ipfs-api');
var fs = require('fs');
var bodyParser = require('body-parser');
var wiki_ipfs;
// connect to ipfs daemon API server
var ipfs = ipfsAPI('localhost', '5001')
var app = express();
app.use( express.static( __dirname + '/client' ));
app.use(bodyParser.json());
app.get('/', function(req,res) {
res.sendFile('./index.html');
});
app.get('/wikis', function(req,res) {
fs.readFile('./client/hashes.json', function(error,data) {
if(error || !data) res.send(console.error(error));
wiki_ipfs = JSON.parse(data);
var wiki_pages = [];
for (var i = 0; i < wiki_ipfs.length; i++) {
var wiki_name = wiki_ipfs[i].name;
wiki_pages.push(wiki_name.toLowerCase());
}
res.send(wiki_pages);
});
});
app.post('/add', function(req,res) {
var new_wiki = req.body.wiki;
var wiki_page = new_wiki['title'];
ipfs.add(new Buffer(JSON.stringify(new_wiki)), function(err, response) {
if(err || !response) res.send(console.error(err));
response.forEach(function(ipfs_obj) {
fs.readFile('./client/hashes.json', function(error,data) {
if(error || !data) res.send(console.error(error));
var stored_wikis = JSON.parse(data);
stored_wikis.push({'hash':ipfs_obj.Hash, 'name': wiki_page});
wiki_ipfs = stored_wikis;
fs.writeFile('./client/hashes.json', JSON.stringify(stored_wikis), function(error2) {
if(error2) res.send(console.error(error2));
res.send("success");
})
});
})
});
});
app.post('/get', function(req,res) {
var wiki_page = req.body.name;
var hash;
if (!wiki_ipfs) {
fs.readFile('./client/hashes.json', function(error,data) {
if(error || !data) return console.error(error);
wiki_ipfs = JSON.parse(data);
});
}
for (var i = 0; i < wiki_ipfs.length; i++) {
if (wiki_ipfs[i].name.toLowerCase() == wiki_page.toLowerCase()) {
hash = wiki_ipfs[i].hash;
break;
}
}
ipfs.cat(hash, function(error, data) {
if(error || !data) res.send(console.error(error));
if(data.readable) {
// Returned as a stream
var wiki_content = '';
data.on('error', function(err) {throw err});
data.on('data', function(obj_content) {
wiki_content += obj_content;
})
data.on('end', function() {
res.send({page:wiki_content.toString()});
})
//
} else {
// Returned as a string
res.send(data);
}
})
});
app.listen(3000, function () {
console.log('Example app listening at http://localhost:3000');
});