Skip to content

Instantly share code, notes, and snippets.

@ruisebastiao
Forked from gpstmp/client-side-pseudo-code.js
Created February 24, 2016 20:58
Show Gist options
  • Save ruisebastiao/5d3550726efd5354504a to your computer and use it in GitHub Desktop.
Save ruisebastiao/5d3550726efd5354504a to your computer and use it in GitHub Desktop.
AngularJS: combine REST with Socket.IO
'use strict';
angular.module('app.api.entities.task', ['app.api.rest.task'])
.factory('Task', ['$rootScope', '$q', 'TaskApi', 'Socket', function($rootScope, $q, TaskApi, Socket) {
// here we use a simple in memory cache in order to keep actual data
// you can make it in any other way
var cache = {};
var initObject = function(data) {
if (cache[data._id]) {
// only extend existed object!!! in order to keep bindings
angular.extend(cache[data._id], new Task(data));
} else {
cache[data._id] = new Task(data);
}
return cache[data._id];
};
var Task = function(data) {
angular.extend(this, data);
};
Task.getAll = function(options) {
var apiResult = TaskApi.getAll(options).then(function(tasks) {
angular.copy({}, cache);
_.map(tasks, function(task) { return initObject(task); });
return cache;
});
if(_.isEmpty(cache)) {
return apiResult;
} else {
return $q.when(cache);
}
};
Task.getOne = function(id) {
return TaskApi.getOne(id).then(function(task) {
return initObject(task);
});
};
Task.create = function(data) {
return TaskApi.create(data).then(function(task) {
return initObject(task);
});
};
Task.prototype.remove = function() {
var self = this;
TaskApi.remove(self._id).then(function() {
delete cache[self._id];
});
};
// incluse SocketIO notifications service that will fire all the listeners on specified evnts
// register listener for NewTask event
Socket.on('NewTask', function(id) {
// plain old REST api call with the id from socket event
Task.getOne(id);
$rootScope.$apply();
});
Socket.on('UpdateTask', function(id) {
Task.getOne(id);
$rootScope.$apply();
});
Socket.on('DeleteTask', function(id) {
delete cache[id];
});
return Task;
}]);
var express = require("express");
var app = module.exports = express();
var Task = require('./task');
// some wrapper for SocketIO lib
var Pusher = require('pusher');
/**
* Create new task from data in request body.
*/
app.post('/task', function(req, res, next) {
Task.create(req.body)
.then(function(task) {
res.data = task;
// emit SocketIO event with the _id of created resource:
// req.body.to - is the _id of the user
// task._id - is the _id of the newly created task
Pusher.event('NewTask').send(req.body.to, task._id);
return next();
})
.catch(next);
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment