Skip to content

Instantly share code, notes, and snippets.

@fitz123
Last active August 21, 2016 21:51
Show Gist options
  • Save fitz123/025daa82637eea53b49601235e91c465 to your computer and use it in GitHub Desktop.
Save fitz123/025daa82637eea53b49601235e91c465 to your computer and use it in GitHub Desktop.
Current Backend API
var express = require('express')
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
var db;
app.use(express.static('static'));
io.on('connection', function(socket){
console.log('a user connected');
function emitDbInsert(doc) {
io.emit('DB Insert', doc);
}
function emitDbDelete(doc) {
io.emit('DB Delete', doc);
}
/* Get a list of filtered records */
app.get('/api/channels', function(req, res) {
console.log("Query: ", req.query);
var filter = {};
if (req.query.location)
filter.location = req.query.location;
if (req.query.resolution)
filter.resolution = req.query.resolution;
db.collection("channels").find(filter).toArray(function(err, docs) {
res.json(docs);
});
});
app.use(bodyParser.json());
/* Insert a record */
app.post('/api/channels/', function(req, res) {
var newCh = req.body;
db.collection("channels").insertOne(newCh, function(err, result) {
var newId = result.insertedId;
console.log("Create:", result.insertedId);
db.collection("channels").find({_id: newId}).next(function(err, doc) {
res.json(doc);
emitDbInsert(doc);
});
});
});
/* Get a single record */
app.get('/api/channels/:id', function(req, res) {
console.log("Read: ", req.params.id);
db.collection("channels").findOne({_id: ObjectId(req.params.id)}, function(err, channel) {
res.json(channel);
});
});
/* Delete a single record */
app.delete('/api/channels/:id', function(req, res) {
console.log("Delete:", req.params.id);
db.collection("channels").deleteOne({_id: ObjectId(req.params.id)}, function(err, channel) {
res.json(channel);
emitDbDelete(req.params.id);
});
});
});
MongoClient.connect('mongodb://localhost/channelsdb', function(err, dbConnection) {
db = dbConnection;
var webapp = server.listen(3000, function() {
var port = webapp.address().port;
console.log("Started webapp at port", port);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment