Browse Source

Added ES6 for backend. Still to add webpack compiling to let us use import, export and classes etc.

Jonathan 8 years ago
parent
commit
8545beffe9

+ 11 - 11
backend/app.js

@@ -5,7 +5,7 @@ const path = require('path'),
       fs   = require('fs'),
       os   = require('os');
 
-process.env.NODE_CONFIG_DIR = process.cwd() + '/backend/config';
+process.env.NODE_CONFIG_DIR = `${process.cwd()}/backend/config`;
 
 // npm modules
 const express          = require('express'),
@@ -29,11 +29,11 @@ const global         = require('./logic/global'),
 // database
 const MongoDB = mongoose.connect('mongodb://localhost:27017/musare').connection;
 
-MongoDB.on('error', function(err) {
+MongoDB.on('error', (err) => {
 	console.log('Database error: ' + err.message);
 });
 
-MongoDB.once('open', function() {
+MongoDB.once('open', () => {
 	console.log('Connected to database');
 });
 
@@ -62,22 +62,22 @@ global.io.use(passportSocketIo.authorize({
 	store: new mongoStore({ mongooseConnection: MongoDB })
 }));
 
-passport.serializeUser(function(user, done) {
+passport.serializeUser((user, done) => {
 	done(null, user);
 });
 
-passport.deserializeUser(function(user, done) {
+passport.deserializeUser((user, done) => {
 	done(null, user);
 });
 
-passport.use('local-signup', new LocalStrategy(function(username, password, cb) {
-	process.nextTick(function() {
+passport.use('local-signup', new LocalStrategy((username, password, cb) => {
+	process.nextTick(() => {
 		db.user.findOne({'username' : username }, function(err, user) {
 			if (err) return cb(err);
 			if (user) return cb(null, false);
 			else {
 				var newUser = new db.user({
-					username: username
+					username
 				});
 				newUser.save(function(err) {
 					if (err) throw err;
@@ -88,9 +88,9 @@ passport.use('local-signup', new LocalStrategy(function(username, password, cb)
 	});
 }));
 
-passport.use('local-login', new LocalStrategy(function(username, password, cb) {
-	process.nextTick(function() {
-		db.user.findOne({'username' : username }, function(err, user) {
+passport.use('local-login', new LocalStrategy((username, password, cb) => {
+	process.nextTick(() => {
+		db.user.findOne({username}, (err, user) => {
 			if (err) return cb(err);
 			if (!user) return cb(null, false);
 			if (!user.services.token.password == password) return done(null, false);

+ 10 - 10
backend/logic/coreHandler.js

@@ -22,31 +22,31 @@ module.exports = {
 
 	// module functions
 
-	on: function (name, cb) {
+	on: (name, cb) => {
 		eventEmitter.on(name, cb);
 	},
 
-	emit: function (name, data) {
+	emit: (name, data) => {
 		eventEmitter.emit(name, data);
 	},
 
 	// core route handlers
 
-	'/users/login': function (user, cb) {
+	'/users/login': (user, cb) => {
 		passport.authenticate('local-login', {
 			// successRedirect: cb({ status: 'success', message: 'Successfully logged in' }),
 			// failureRedirect: cb({ status: 'error', message: 'Error while trying to log in' })
 		});
 	},
 
-	'/users/register': function (user, cb) {
+	'/users/register': (user, cb) => {
 		passport.authenticate('local-signup', {
 			// successRedirect: cb({ status: 'success', message: 'Successfully signed up' }),
 			// failureRedirect: cb({ status: 'error', message: 'Error while trying to sign up' })
 		});
 	},
 
-	'/stations': function (cb) {
+	'/stations': cb => {
 		cb(stations.getStations().map(function (result) {
 			return {
 				id: result.getId(),
@@ -57,9 +57,9 @@ module.exports = {
 		}));
 	},
 
-	'/stations/join/:id': function (id, user, cb) {
+	'/stations/join/:id': (id, user, cb) => {
 
-		var station = stations.getStation(id);
+		const station = stations.getStation(id);
 
 		if (station) {
 
@@ -86,9 +86,9 @@ module.exports = {
 		}
 	},
 
-	'/stations/search/:query': function (query, cb) {
+	'/stations/search/:query': (query, cb) => {
 
-		var params = [
+		const params = [
 			'part=snippet',
 			`q=${encodeURIComponent(query)}`,
 			`key=${config.get('apis.youtube.key')}`,
@@ -96,7 +96,7 @@ module.exports = {
 			'maxResults=25'
 		].join('&');
 
-		request(`https://www.googleapis.com/youtube/v3/search?${params}`, function (err, res, body) {
+		request(`https://www.googleapis.com/youtube/v3/search?${params}`, (err, res, body) => {
 			if (err) {
 				return cb({ status: 'error', message: 'Failed to make request' });
 			}

+ 11 - 11
backend/logic/expressHandler.js

@@ -1,41 +1,41 @@
 'use strict';
 
-module.exports = function (core, app) {
+module.exports = (core, app) => {
 
-	app.post('/users/login', function (req, res) {
+	app.post('/users/login', (req, res) => {
 
 		// TODO: Give this a better error message
 		if (!req.body.user) {
 			return res.send(JSON.stringify({ 'status': 'error', 'message': 'invalid request' }));
 		}
 
-		core['/users/login'](req.body.user, function (result) {
+		core['/users/login'](req.body.user, result => {
 			res.send(JSON.stringify(result));
 			console.log(JSON.stringify(result));
 		});
 	});
 
-	app.post('/users/register', function (req, res) {
-		core['/users/register'](req.body.user, function (result) {
+	app.post('/users/register', (req, res) => {
+		core['/users/register'](req.body.user, (result) => {
 			res.send(JSON.stringify(result));
 		});
 		console.log('posted');
 	});
 
-	app.get('/stations', function (req, res) {
-		core['/stations'](function (result) {
+	app.get('/stations', (req, res) => {
+		core['/stations'](result => {
 			res.send(JSON.stringify(result));
 		});
 	});
 
-	app.get('/stations/join/:id', function (req, res) {
-		core['/stations/join/:id'](req.params.id, function (result) {
+	app.get('/stations/join/:id', (req, res) => {
+		core['/stations/join/:id'](req.params.id, result => {
 			res.send(JSON.stringify(result));
 		});
 	});
 
-	app.get('/stations/search/:query', function (req, res) {
-		core['/stations/search/:query'](req.params.query, function (result) {
+	app.get('/stations/search/:query', (req, res) => {
+		core['/stations/search/:query'](req.params.query, result => {
 			res.send(JSON.stringify(result));
 		});
 	});

+ 8 - 8
backend/logic/global.js

@@ -1,26 +1,26 @@
 function Timer(callback, delay, paused) {
-	var timerId, start, remaining = delay;
-	var timeWhenPaused = 0;
-	var timePaused = Date.now();
+	let timerId, start, remaining = delay;
+	let timeWhenPaused = 0;
+	const timePaused = Date.now();
 
-	this.pause = function () {
+	this.pause = () => {
 		clearTimeout(timerId);
 		remaining -= Date.now() - start;
 		timePaused = Date.now();
 	};
 
-	this.resume = function () {
+	this.resume = () => {
 		start = Date.now();
 		clearTimeout(timerId);
 		timerId = setTimeout(callback, remaining);
 		timeWhenPaused += Date.now() - timePaused;
 	};
 
-	this.resetTimeWhenPaused = function() {
+	this.resetTimeWhenPaused = () => {
 		timeWhenPaused = 0;
 	};
 
-	this.timeWhenPaused = function () {
+	this.timeWhenPaused = () => {
 		return timeWhenPaused;
 	};
 
@@ -35,5 +35,5 @@ module.exports = {
 	htmlEntities: function(str) {
 		return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
 	},
-	Timer: Timer
+	Timer
 };

+ 15 - 15
backend/logic/socketHandler.js

@@ -1,48 +1,48 @@
 'use strict';
 
-module.exports = function (core, io) {
+module.exports = (core, io) => {
 
 	// tell all the users in this room that someone is joining it
-	core.on('station-joined', function (user) {
-		io.sockets.clients().forEach(function (socket) {
+	core.on('station-joined', user => {
+		io.sockets.clients().forEach(socket => {
 			if (socket.request.user.id != user.user.id && socket.request.user.roomId === id) {
 				socket.emit('station-joined', user);
 			}
 		});
 	});
 
-	io.on('connection', function (socket) {
+	io.on('connection', socket => {
 
-		socket.on('disconnect', function () {
+		socket.on('disconnect', () => {
 			console.log('User has disconnected');
 		});
 
-		socket.on('/users/login', function (user, cb) {
-			core['/users/login'](user, function (result) {
+		socket.on('/users/login', (user, cb) => {
+			core['/users/login'](user, result => {
 				cb(result);
 			});
 		});
 
-		socket.on('/users/register', function (user, cb) {
-			core['/users/register'](user, function (result) {
+		socket.on('/users/register', (user, cb) => {
+			core['/users/register'](user, result => {
 				cb(result);
 			});
 		});
 
-		socket.on('/stations', function (cb) {
-			core['/stations'](function (result) {
+		socket.on('/stations', cb => {
+			core['/stations'](result => {
 				cb(result);
 			});
 		});
 
-		socket.on('/stations/join/:id', function (id, cb) {
-			core['/stations/join/:id'](id, function (result) {
+		socket.on('/stations/join/:id', (id, cb) => {
+			core['/stations/join/:id'](id, result => {
 				cb(result);
 			});
 		});
 
-		socket.on('/stations/search/:query', function (query, cb) {
-			core['/stations/search/:query'](query, function (result) {
+		socket.on('/stations/search/:query', (query, cb) => {
+			core['/stations/search/:query'](query, result => {
 				cb(result);
 			});
 		});

+ 39 - 39
backend/logic/stations.js

@@ -5,25 +5,25 @@ var io = global.io;
 
 function Station (id, data) {
 
-	var self = this;
+	const self = this;
 
 	//TODO Add startedAt and timePaused
-	var playlist = data.playlist;
-	var currentSong = playlist[0];
-	var currentSongIndex = data.currentSongIndex;
-	var paused = data.paused;
-	var locked = data.locked;
-	var skipVotes = data.skipVotes;
-	var users = data.users;
-	var displayName = data.displayName;
-	var description = data.description;
-	var timer;
-	var nsp = io.of('/' + id);
-	nsp.on('connection', function(socket){
+	let playlist = data.playlist;
+	let currentSong = playlist[0];
+	let currentSongIndex = data.currentSongIndex;
+	let paused = data.paused;
+	let locked = data.locked;
+	let skipVotes = data.skipVotes;
+	let users = data.users;
+	let displayName = data.displayName;
+	let description = data.description;
+	let timer;
+	let nsp = io.of('/' + id);
+	nsp.on('connection', socket => {
 		console.log('someone connected');
 	});
 
-	this.skipSong = function() {
+	this.skipSong = () => {
 		if (playlist.length > 0) {
 			if (timer !== undefined) {
 				timer.pause();
@@ -35,7 +35,7 @@ function Station (id, data) {
 			}
 			skipVotes = 0;
 			currentSong = playlist[currentSongIndex];
-			timer = new global.Timer(function() {
+			timer = new global.Timer(() => {
 				console.log("Skip!");
 				self.skipSong();
 			}, currentSong.duration, paused);
@@ -43,7 +43,7 @@ function Station (id, data) {
 			nsp.emit("skippedSong", currentSong);
 		}
 	};
-	this.toggleVoteSkip = function(userId) {
+	this.toggleVoteSkip = userId => {
 		if (skipVotes.indexOf(userId) === -1) {
 			skipVotes.push(userId);
 		} else {
@@ -52,72 +52,72 @@ function Station (id, data) {
 		//TODO Calculate if enough people voted to skip
 		nsp.emit("voteSkip", skipVotes);
 	};
-	this.retrievePlaylist = function() {
+	this.retrievePlaylist = () => {
 		//TODO Use Rethink to get the Playlist for this station
 	};
-	this.pause = function() {
+	this.pause = () => {
 		if (!paused) {
 			paused = true;
 			timer.pause();
 			nsp.emit("pause");
 		}
 	};
-	this.unpause = function() {
+	this.unpause = () => {
 		if (paused) {
 			paused = false;
 			timer.resume();
 			nsp.emit("unpause");
 		}
 	};
-	this.isPaused = function() {
+	this.isPaused = () => {
 		return paused;
 	};
-	this.getCurrentSong = function() {
+	this.getCurrentSong = () => {
 		return currentSong;
 	};
-	this.lock = function() {
+	this.lock = () => {
 		if (!locked) {
 			locked = true;
 			nsp.emit("lock");
 		}
 	};
-	this.unlock = function() {
+	this.unlock = () => {
 		if (locked) {
 			locked = false;
 			nsp.emit("unlocked");
 		}
 	};
-	this.isLocked = function() {
+	this.isLocked = () => {
 		return locked;
 	};
-	this.updateDisplayName = function(newDisplayName) {
+	this.updateDisplayName = newDisplayName => {
 		//TODO Update RethinkDB
 		displayName = newDisplayName;
 		nsp.emit("updateDisplayName", newDisplayName);
 	};
-	this.updateDescription = function(newDescription) {
+	this.updateDescription = newDescription => {
 		//TODO Update RethinkDB
 		description = newDescription;
 		nsp.emit("updateDescription", newDescription);
 	};
-	this.getId = function() {
+	this.getId = () => {
 		return id;
 	};
-	this.getDisplayName = function() {
+	this.getDisplayName = () => {
 		return displayName;
 	};
-	this.getDescription = function() {
+	this.getDescription = () => {
 		return description;
 	};
-	this.addUser = function(user) {
+	this.addUser = user => {
 		users.add(user);
 		nsp.emit("updateUsers", users);
 	};
-	this.removeUser = function(user) {
+	this.removeUser = user => {
 		users.splice(users.indexOf(user), 1);
 		nsp.emit("updateUsers", users);
 	};
-	this.getUsers = function() {
+	this.getUsers = () => {
 		return users;
 	};
 	this.skipSong();
@@ -127,9 +127,9 @@ module.exports = {
 
 	stations: [],
 
-	initStation: function (id, data) {
+	initStation: (id, data) => {
 		if (!this.getStation(id)) {
-			var station = new Station(id, data);
+			let station = new Station(id, data);
 			this.stations.push(station);
 			return station;
 		}
@@ -138,26 +138,26 @@ module.exports = {
 		}
 	},
 
-	getStation: function (id) {
-		var s = null;
+	getStation: id => {
+		let s = null;
 		this.stations.forEach(function (station) {
 			if (station.id == id) s = station;
 		});
 		return s;
 	},
 
-	getStations: function () {
+	getStations: () => {
 		return this.stations;
 	},
 
 	// creates a brand new station
-	createStation: function (data) {
+	createStation: data => {
 		//TODO: add createStation functionality
 		this.initStation(null, data);
 	},
 
 	// loads a station from the database
-	loadStation: function (id) {
+	loadStation: id => {
 		//TODO: Get the data from RethinkDB
 		this.initStation(id, {
 			playlist: [

+ 1 - 1
backend/schemas/station.js

@@ -1,4 +1,4 @@
-module.exports = function(mongoose) {
+module.exports = mongoose => {
 
 	var Schema = mongoose.Schema;
 

+ 2 - 2
backend/schemas/user.js

@@ -1,4 +1,4 @@
-module.exports = function(mongoose) {
+module.exports = mongoose => {
 
     var Schema = mongoose.Schema;
 
@@ -40,4 +40,4 @@ module.exports = function(mongoose) {
     });
 
     return mongoose.model('user', userSchema);
-}
+}