Skip to content

Commit

Permalink
Add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kierzniak committed Mar 15, 2018
1 parent b162d10 commit a011955
Show file tree
Hide file tree
Showing 12 changed files with 159 additions and 16 deletions.
22 changes: 22 additions & 0 deletions lib/db/mongodb.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import mongoose from "mongoose";
import logger from "winston";

import { mongodburl } from "./../config/";

mongoose.connection.on("connected", function() {
logger.info("MongoDB connected.");
});

mongoose.connection.once("open", function() {
logger.info("MongoDB connection opened.");
});

mongoose.connection.on("disconnected", function() {
logger.info("MongoDB disconnected.");
});

mongoose.connection.on("reconnected", function() {
logger.info("MongoDB reconnected.");
});

mongoose.connection.on("error", function(err) {
logger.error("MongoDB error.");
logger.error(err);
});

mongoose.connect(mongodburl);
15 changes: 15 additions & 0 deletions lib/respositories/image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import Image from "./../models/image";

export default {
findById(id) {
return new Promise(function(resolve, reject) {
Image.findById(id, function(err, image) {
if (err) {
return reject(err);
}

resolve(image);
});
});
}
};
3 changes: 3 additions & 0 deletions lib/respositories/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import image from "./image.js";

export { image };
4 changes: 0 additions & 4 deletions lib/services/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,14 @@ class ImageService {
let buffer, publicPath, basePath, filePath;

logger.info("Image optimization: Find image.");

image = await Image.findById(image.id);

logger.info("Image optimization: Start image optimization.");

buffer = await imagemin.buffer(fs.readFileSync(image.path), {
plugins: [imageminMozjpeg(), imageminJpegoptim(), imageminPngquant()]
});

logger.info("Image optimization: Save optimized image to public path.");

publicPath = config.get("public");

if (!fs.existsSync(publicPath)) {
Expand All @@ -110,7 +107,6 @@ class ImageService {
fs.writeFileSync(filePath, buffer);

logger.info("Image optimization: Update image model.");

image.optimized = true;
image.optimized_path = filePath;
image.optimized_size = image.resolveSize();
Expand Down
16 changes: 13 additions & 3 deletions lib/web/controllers/image.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Image from "./../../models/image";
import boom from "boom";

import { image as ImageRepository } from "./../../respositories";

/**
* Image action.
Expand All @@ -9,8 +11,16 @@ import Image from "./../../models/image";
* @returns {void} Returns nothing.
*/
async function image(req, res) {
let image = await Image.findById(req.params.id);
let response = Object.assign({}, { success: true }, image.toJSON());
let image;
let response;

image = await ImageRepository.findById(req.params.id);

if (image === null) {
throw boom.notFound(`No image found for id ${req.params.id}`);
}

response = Object.assign({}, { success: true }, image.toJSON());

res.status(200);
res.json(response);
Expand Down
25 changes: 25 additions & 0 deletions lib/web/middlewares/error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import boom from "boom";

/**
* Error middleware.
*
* Error middleware will catch any error throwed in controllers
* and pass it to express next function.
*
* @param {Function} fn - Express route controller action.
*
* @returns {Function} Express middleware function.
*/
function error(fn) {
return function(req, res, next) {
Promise.resolve(fn(req, res, next)).catch(err => {
if (!err.isBoom) {
return next(boom.badImplementation(err));
}

return next(err);
});
};
}

export default error;
3 changes: 2 additions & 1 deletion lib/web/routes/image.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import error from "./../middlewares/error.js";
import { image as imageAction } from "./../controllers/image.js";

/**
Expand All @@ -9,7 +10,7 @@ import { image as imageAction } from "./../controllers/image.js";
*/
function image(app) {
// Get image route
app.route("/image/:id").get(imageAction);
app.route("/image/:id([a-f\\d]{24})").get(error(imageAction));
}

export default image;
25 changes: 25 additions & 0 deletions lib/web/routes/notfound.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import boom from "boom";

import error from "./../middlewares/error.js";

/**
* Not found route.
*
* Throw not found error if any routes get here.
*
* @param {Object} app - Express app.
*
* @returns {void} Returns nothing.
*/
function notfound(app) {
// Match all routes
app.route("*").get(
error(function(req, res) {
throw boom.notFound(
"The URI requested is invalid or the resource requested does not exist."
);
})
);
}

export default notfound;
3 changes: 2 additions & 1 deletion lib/web/routes/optimize.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import error from "./../middlewares/error.js";
import validate from "./../middlewares/validator.js";
import imageHandler from "./../middlewares/handlers/image.js";

Expand All @@ -15,7 +16,7 @@ function optimize(app) {
// Optimize image route
app
.route("/optimize")
.post(validate(optimizeValidator), imageHandler, optimizeAction);
.post(validate(optimizeValidator), imageHandler, error(optimizeAction));
}

export default optimize;
35 changes: 35 additions & 0 deletions lib/web/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import bodyParser from "body-parser";

import optimizeRoutes from "./routes/optimize.js";
import imageRoutes from "./routes/image.js";
import notfoundRoutes from "./routes/notfound.js";

/**
* Init web server.
Expand All @@ -23,10 +24,44 @@ function web() {

optimizeRoutes(app);
imageRoutes(app);
notfoundRoutes(app);

app.use(errors);

logger.info(`Starting Motimize web REST API server on ${port} port.`);

app.listen(port);
}

/**
* Error handler.
*
* @param {Object} err - Error object.
* @param {Object} req - Express request object.
* @param {Object} res - Express response object.
* @param {Function} next - Express next function.
*
* @returns {void} Returns nothing.
*/
function errors(err, req, res, next) {
/* Log error internaly */
logger.error(err);

/**
* Remove Error's `stack` property. We don't want
* users to see this at the production env
*/
if (
process.env.NODE_ENV !== "development" ||
process.env.NODE_ENV !== "test"
) {
delete err.stack;
}

/* Finaly respond to the request */
res
.status(err.output.statusCode || 500)
.json({ success: false, message: err.output.payload.message });
}

export default web;
18 changes: 11 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"babel-core": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.26.0",
"boom": "^7.2.0",
"bull": "^3.3.10",
"dotenv": "^5.0.1",
"download": "^6.2.5",
Expand Down Expand Up @@ -79,14 +80,17 @@
"jsdoc/require-param-type": "error",
"jsdoc/require-returns-description": "error",
"jsdoc/require-returns-type": "error",
"require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": true,
"MethodDefinition": true,
"ClassDeclaration": true,
"ArrowFunctionExpression": true
"require-jsdoc": [
"error",
{
"require": {
"FunctionDeclaration": true,
"MethodDefinition": true,
"ClassDeclaration": true,
"ArrowFunctionExpression": true
}
}
}],
],
"valid-jsdoc": "error"
}
},
Expand Down
6 changes: 6 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,12 @@ [email protected]:
dependencies:
hoek "4.x.x"

boom@^7.2.0:
version "7.2.0"
resolved "https://registry.yarnpkg.com/boom/-/boom-7.2.0.tgz#2bff24a55565767fde869ec808317eb10c48e966"
dependencies:
hoek "5.x.x"

boxen@^1.2.1:
version "1.3.0"
resolved "https://registry.yarnpkg.com/boxen/-/boxen-1.3.0.tgz#55c6c39a8ba58d9c61ad22cd877532deb665a20b"
Expand Down

0 comments on commit a011955

Please sign in to comment.