From 44e55d2a98f068d08bf02dfcc2270b23a7052409 Mon Sep 17 00:00:00 2001 From: Peter Jaszkowiak Date: Mon, 29 May 2017 12:35:55 -0600 Subject: [PATCH] Less synchronous stuffs --- src/controllers/admin/themes.js | 56 ++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/src/controllers/admin/themes.js b/src/controllers/admin/themes.js index 94fdf43746..cd70522fc9 100644 --- a/src/controllers/admin/themes.js +++ b/src/controllers/admin/themes.js @@ -1,25 +1,53 @@ 'use strict'; var path = require('path'); +var fs = require('fs'); +var async = require('async'); + var file = require('../../file'); var themesController = {}; +var defaultScreenshotPath = path.join(__dirname, '../../../public/images/themes/default.png'); + themesController.get = function (req, res, next) { - var themeDir = path.join(__dirname, '../../../node_modules/' + req.params.theme); - file.exists(themeDir, function (err, exists) { - if (err || !exists) { - return next(err); - } - - var themeConfig = require(path.join(themeDir, 'theme.json')); - var screenshotPath = path.join(themeDir, themeConfig.screenshot); - if (themeConfig.screenshot && file.existsSync(screenshotPath)) { - res.sendFile(screenshotPath); - } else { - res.sendFile(path.join(__dirname, '../../../public/images/themes/default.png')); - } - }); + var themeDir = path.join(__dirname, '../../../node_modules', req.params.theme); + var themeConfigPath = path.join(themeDir, 'theme.json'); + + async.waterfall([ + function (next) { + file.exists(themeConfigPath, function (err, exists) { + if (err) { + return next(err); + } + if (!exists) { + return next(Error('invalid-data')); + } + + next(); + }); + }, + function (next) { + fs.readFile(themeConfigPath, next); + }, + function (themeConfig, next) { + try { + themeConfig = JSON.parse(themeConfig); + next(null, themeConfig.screenshot ? path.join(themeDir, themeConfig.screenshot) : defaultScreenshotPath); + } catch (e) { + next(e); + } + }, + function (screenshotPath, next) { + file.exists(screenshotPath, function (err, exists) { + if (err) { + return next(err); + } + + res.sendFile(exists ? screenshotPath : defaultScreenshotPath); + }); + }, + ], next); }; module.exports = themesController;