-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (64 loc) · 2.03 KB
/
index.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
/* jshint node:true */
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var baucis = require('baucis');
var http = require('http');
var faye = require('faye');
var mongooseUtils = require('./lib/mongoose-utils');
var Schema = mongoose.Schema;
// The mongoose schema used by the Todo list demo
var todoSchema = new Schema({
title: String,
completed: Boolean
});
// This method will send realtime notifications to the faye clients
function notifyClients(method, model, url) {
fayeServer.getClient().publish(url, {
method: method,
body: model.toJSON()
});
}
// Attach events to the mongoose schema. Since the default mongoose middleware makes it difficult to
// distinguish between a create and an update event, we use a small utility that helps us to do that.
mongooseUtils.attachListenersToSchema(todoSchema, {
onCreate: function(model, next) {
notifyClients('POST', model, '/api/todos');
next();
},
onUpdate: function(model, next) {
notifyClients('PUT', model, '/api/todos');
next();
},
onRemove: function(model) {
notifyClients('DELETE', model, '/api/todos');
}
});
// Create a mongoose model
var Todo = mongoose.model('todo', todoSchema);
// Connect to Mongo
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/todo');
var app = express();
var server = http.createServer(app);
app.use(express.static('public'));
baucis.rest({
singular: 'todo',
plural: 'todos',
del: function(req, res, next) {
// Baucis' delete doesn't invoke the middleware (as it's using Model.remove())
// So we'll override the default delete method with out own that does involk the middleware
// on deletion.
Todo.findById(req.params.id, function(err, todo) {
if(err) return next(401);
if(!todo) return next(404);
todo.remove(function(err) {
if(err) return next(401);
res.send(200);
});
});
}
});
app.use('/api/', baucis());
var fayeServer = new faye.NodeAdapter({mount: '/faye', timeout: 45});
fayeServer.attach(server);
server.listen(process.env.NODE_PORT || 3000);