Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled server error response handler #41

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const serverMethods = require('../helpers/server-methods');
const slack = require('../helpers/slack');
const resetScript = require('../scripts/reset');
const logger = require('../helpers/logger');
const { serverErrorResponse } = require('../responses');

const { app: appConfig } = require('../config');

Expand Down Expand Up @@ -93,8 +94,7 @@ module.exports = {
data: playlist,
});
} catch (err) {
logger.error(err);
return res.status(500).send({ message: 'An error occurred' });
return serverErrorResponse(res, err);
}
},

Expand Down
10 changes: 10 additions & 0 deletions controllers/notFound.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const { clientErrorResponse } = require('../responses');

/**
* Controller for handling routes that don't exist
* @param {*} req
* @param {*} res
*/
const notFound = (req, res) => clientErrorResponse(res, 400, 'This route doesn\'t exist yet');

module.exports = notFound;
32 changes: 16 additions & 16 deletions controllers/playlist.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
const spotify = require('../helpers/spotify');
const logger = require('../helpers/logger');
const {
successResponse,
clientErrorResponse,
serverErrorResponse,
} = require('../responses');

module.exports = {

/**
* Retrieve a single playlist
*/
getPlaylistByID: async (req, res) => {
try {
const { id } = req.params;

const playlist = await spotify.findPlaylist(id);
if (!playlist) {
return res.status(404).send({
status: false,
message: 'Playlist not found',
});
return clientErrorResponse(res, 404, 'Playlist not found');
}
return res.status(200).send({
status: true,
data: playlist,
});
return successResponse(res, 200, 'Playlist retrieved', playlist);
} catch (err) {
logger.error(err);
return res.status(500).send({ status: false, message: 'An error occurred' });
return serverErrorResponse(res, err);
}
},

/**
* Retrieve all playlists
*/
getAllPlaylists: async (req, res) => {
try {
const playlists = await spotify.findAllPlaylists();
return res.status(200).send({
status: true,
data: playlists,
});
return successResponse(res, 200, 'Playlists retrieved', playlists);
} catch (err) {
return res.status(500).send({ status: false, message: 'An error occurred' });
return serverErrorResponse(res, err);
}
},
};
39 changes: 19 additions & 20 deletions controllers/track.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
const spotify = require('../helpers/spotify');
const logger = require('../helpers/logger');
const {
successResponse,
clientErrorResponse,
serverErrorResponse,
} = require('../responses');

module.exports = {

/**
* Get track audio features
*/
getTrackAudioFeatures: async (req, res) => {
try {
const tracks = await spotify.findTracksWithoutAnalytics();
if (!tracks.length) return res.status(200).send({ status: true, message: 'All tracks have their analytics set' });
await spotify.performAuthentication();
spotify.getAudioAnalyticsForTracks(tracks);
return res.status(200).send({
status: true,
message: 'Populating analytics...',
});
return successResponse(res, 200, 'Populating analytics...');
} catch (err) {
logger.error(err);
return res.status(500).send({ message: 'An error occurred' });
return serverErrorResponse(res, err);
}
},

Expand All @@ -24,35 +27,31 @@ module.exports = {
const tracks = await spotify.findTracksWithoutPreview();
if (!tracks.length) return res.status(200).send({ status: true, message: 'All tracks have their previews set' });
await spotify.performAuthentication();

await spotify.getPreviewUrlForTracks(tracks);
return res.status(200).send({
status: true,
message: 'Previews have been populated.',
});
return successResponse(res, 200, 'Previews have been populated');
} catch (err) {
logger.error(err);
return res.status(500).send({ message: 'An error occurred' });
return serverErrorResponse(res, err);
}
},

/**
* Get track data
*/
getTrackData: async (req, res) => {
try {
const { track_ids: ids } = req.body;

const result = await spotify.performAuthentication();
if (result && result.code === 401) {
return res.status(401).send({ message: result.message });
return clientErrorResponse(res, result.code, result.message);
}

const data = await spotify.getTrackData(ids);

return res.status(200).send({
status: true,
data,
});
return successResponse(res, 200, 'Track data retrieved', data);
} catch (err) {
logger.error(err);
return res.status(500).send({ message: 'An error occurred' });
return serverErrorResponse(res, err);
}
},
};
41 changes: 41 additions & 0 deletions responses/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const logger = require('../helpers/logger');
const slack = require('../helpers/slack');

/**
* Handler for success responses
* @param {Object} res
* @param {Number} code
* @param {String} message
* @param {Array|Object} data
*/
const successResponse = (res, code, message, data) => (
res.status(code).send({ success: true, message, data })
);

/**
* Method to return client error responses
* @param {Object} res
* @param {Number} code
* @param {String} message
*/
const clientErrorResponse = (res, code, message) => (
res.status(code).send({ success: false, message })
);

/**
* Method to return 5xx errors
* @param {Object} res
* @param {Object} error
* @param {Number} code
*/
const serverErrorResponse = (res, error, code = 500) => {
logger.error(error);
slack.sendMonitorMessage(error);
return res.status(code).send({ success: false, message: 'An error occurred' });
};

module.exports = {
successResponse,
clientErrorResponse,
serverErrorResponse,
};
9 changes: 9 additions & 0 deletions routes/notFound.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express');

const router = express.Router();

const notFound = require('../controllers/notFound');

router.get('/', notFound);

module.exports = router;
2 changes: 2 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const logger = require('./helpers/logger');
const indexRouter = require('./routes/index');
const playlistRouter = require('./routes/playlists');
const trackRouter = require('./routes/track');
const notFoundRouter = require('./routes/notFound');

require('./config/db');

Expand All @@ -26,6 +27,7 @@ app.disable('x-powered-by');
app.use('/', indexRouter);
app.use('/playlists', playlistRouter);
app.use('/track', trackRouter);
app.use('*', notFoundRouter);

// listen for requests :)
const listener = app.listen(appConfig.port, () => {
Expand Down