socket.io in an express app

Socket.io’s Documentation on how to use it with expressjs is slightly not-so-useful. Most likely you will have some MVCish pattern and your controller is far away from where your app lives. I guess you are using express.Router() (at least you should), making it even more difficult to pass the socket.io instance through some require calls. A solution to this occurred to me in the shower.

For simplifying things I wrote this in one file.

var http = require('http')
  , express = require('express')
  , socketio = require('socket.io');
var app = express()
  , sio = socketio();

 * Middleware
// This attaches the socket.io instance
// to the request object
app.use(function(req, res, next) {
  req.io = sio; next();

// More middleware, like the following
app.use(express.static(path.join(__dirname, './public')));

 * Router
app.get('/', function(req, res) {
  req.io.sockets.emit('hi', { hello: 'world' });
  res.send('Hello World');

 * Server creation
var server = http.createServer(app);

Response Builder for express and mongoose

This article is very nerdy and probably not interesting and/or understandable if you’re not a nerd-node-programmer. Instead watch this cute sleepy duckling.

tl;dr I made a small node module, it’s a simple file, take this gist, check it out, maybe it is useful.

Today I ran into a few problems with my mongoose models. Everything got messy and it felt like I was fixing something in one function and a causing a bug in another function. Before I go on I summarize my struggle shortly:

  • I have two models: an user model and an upload model.
  • The user model references to all uploads of an user. The upload model references to the user which uploaded the file.
  • I have a method in the upload model which needs to access data from the populated user model.
  • The model’s response isn’t the schema. I transform it before sending it.
  • I want a clean and unified response object model.
  • The controller shouldn’t end in a big mess.

Understood it? Me neither. What a fucking mess. I lost track of my files, functions were all over the place, and lastly I tried to populate the models which caused bugs everywhere. It felt like I need to sit in my shower, drink a really bad whisky and cry a lot.