I'm trying to use gun in an express/node project, however I want to mount the endpoint as /db
. I had hoped the following code would work but keep getting a Route.get() requires callback functions error:
var express = require('express');
var Gun = require('gun');
var app = express();
var port = 8080;
var gun = new Gun({
file: './data.json'
});
// mount the gun db server
app.get('/db', gun.router);
// regular express route
app.get('/', function(req, res) {
res.send('other stuff...');
});
// start the server
app.listen(port, function () {
console.log('Web server listening on port ' + port);
});
Any suggestions?
Doherty!
GUN can be used with express, but it is not an express route. For example, lets first go over a simple gun server mounted with express:
var express = require('express');
var Gun = require('gun');
var app = express();
app.use(Gun.serve).use(express.static(__dirname));
var server = app.listen(80);
Gun({file: 'data.json', web: server});
( https://github.com/amark/gun/blob/master/examples/express.js )
GUN's API is now available in the browser at:
<script src="http://YOURSERVER.com/gun.js"></script>
<script>
var gun = Gun('http://YOURSERVER.com/gun');
gun.get('key').get('hello').put('world!');
gun.get('key').get('hello').on(function(data){ console.log(data) });
</script>
GUN is not available as an express route. For example, this does not work:
http://YOURSERVER.com/data/key/hello?put=world!
GUN is a realtime database, if you use a REST or CRUD routes with express as its API, then you lose the realtime capabilities. Meaning you would have to write your own custom long-polling implementation, which defeats the point of having an express route.
It should not be hard to create an HTTP route that proxies gun. Here is some pseudocode that should help get you started. If you build it, please make it an Open Source module on NPM so others can enjoy it!!!
// this is pseudocode!!!
app.get('/data', (req, res) => {
path(req).val(data => res.send(data))
});
app.put('/data', (req, res) => {
path(req).put(req.param.put, ack => {
res.ack? 0 : res.ack = res.send(ack)
})
});
var path = (req) => {
var ref = gun;
req.path.split('/').forEach(key => ref = ref.get(key));
return ref;
}
Let us know if you build it! As always, the community chatroom is friendly and active. Ask for help there, and ask questions here. Thanks for making this a SO question!