Files
panic-server/src/server.js
Jesse Gibson 7425aaac2d Rename .len() to .length, allow subclassing, export client bundle.
Instead of calling a method to find the length of a list, you can use a
property (which is a getter under the hood, doing the same thing as
`.len()`). This is cleaner and more intuitive, aligning itself more with
arrays.
Subclassing is now facilitated by a new method, `.chain`. It creates a
new list instance by calling the constructor property, instead of
statically creating a new ClientList instance. This allows you to
create subclasses that inherit from ClientList, without losing that
inheritance when calling `.filter` or `.pluck` (methods which create new
list instances).
The client bundle is now exported lazily, so when you import panic,
there's a `client` getter which memoizes a fs call for the client code.
This allows compatibility on pre-3.0 versions of npm, where other packages
might not be able to recursively find `panic-client`. Also, since it's a
getter, it doesn't do the file system call until it's needed.
2016-05-28 21:16:23 -06:00

49 lines
854 B
JavaScript

/*eslint-disable no-sync*/
'use strict';
var io = require('socket.io');
var fs = require('fs');
var clients = require('./clients');
var file = require.resolve('panic-client/panic.js');
var Server = require('http').Server;
var panic = require('./index');
var client;
Object.defineProperty(panic, 'client', {
get: function () {
if (!client) {
client = fs.readFileSync(file, 'utf8');
}
return client;
}
});
function serve(req, res) {
if (req.url === '/panic.js') {
res.end(panic.client);
}
}
function upgrade(socket) {
socket.on('handshake', function (platform) {
clients.add({
socket: socket,
platform: platform
});
});
}
function open(server) {
if (!(server instanceof Server)) {
server = new Server();
}
server.on('request', serve);
io(server).on('connection', upgrade);
return server;
}
module.exports = open;