diff --git a/lib/cartodb/controllers/analyses.js b/lib/cartodb/controllers/analyses.js index a977c854..eab5056b 100644 --- a/lib/cartodb/controllers/analyses.js +++ b/lib/cartodb/controllers/analyses.js @@ -19,11 +19,51 @@ AnalysesController.prototype.register = function(app) { userMiddleware, this.prepareContext, this.catalog.bind(this), + this.prepareResponse(), this.setCacheControlHeader(), this.sendResponse() ); }; +AnalysesController.prototype.prepareResponse = function () { + return function prepareResponseMiddleware (req, res, next) { + const { catalogWithTables } = res.locals; + + const analysisIdToTable = catalogWithTables.tables.reduce((analysisIdToTable, table) => { + const analysisId = table.relname.split('_')[2]; + if (analysisId && analysisId.length === 40) { + analysisIdToTable[analysisId] = table; + } + return analysisIdToTable; + }, {}); + + const catalog = catalogWithTables.catalog.map(analysis => { + if (analysisIdToTable.hasOwnProperty(analysis.node_id)) { + analysis.table = analysisIdToTable[analysis.node_id]; + } + return analysis; + }) + .sort((analysisA, analysisB) => { + if (!!analysisA.table && !!analysisB.table) { + return analysisB.table.size - analysisA.table.size; + } + + if (!!analysisA.table) { + return -1; + } + + if (!!analysisB.table) { + return 1; + } + + return -1; + }); + + res.body = { catalog }; + next(); + }; +}; + AnalysesController.prototype.setCacheControlHeader = function () { return function setCacheControlHeaderMiddleware (req, res, next) { res.set('Cache-Control', 'public,max-age=10,must-revalidate'); @@ -51,40 +91,6 @@ AnalysesController.prototype.catalog = function (req, res, next) { var pg = new PSQL(dbParamsFromReqParams(res.locals)); getMetadata(username, pg, this); }, - function prepareResponse(err, results) { - assert.ifError(err); - - var analysisIdToTable = results.tables.reduce(function(analysisIdToTable, table) { - var analysisId = table.relname.split('_')[2]; - if (analysisId && analysisId.length === 40) { - analysisIdToTable[analysisId] = table; - } - return analysisIdToTable; - }, {}); - - var catalogWithTables = results.catalog.map(function(analysis) { - if (analysisIdToTable.hasOwnProperty(analysis.node_id)) { - analysis.table = analysisIdToTable[analysis.node_id]; - } - return analysis; - }); - - return catalogWithTables.sort(function(analysisA, analysisB) { - if (!!analysisA.table && !!analysisB.table) { - return analysisB.table.size - analysisA.table.size; - } - - if (!!analysisA.table) { - return -1; - } - - if (!!analysisB.table) { - return 1; - } - - return -1; - }); - }, function prepareResponse(err, catalogWithTables) { if (err) { if (err.message.match(/permission\sdenied/)) { @@ -95,7 +101,7 @@ AnalysesController.prototype.catalog = function (req, res, next) { return next(err); } - res.body = { catalog: catalogWithTables }; + res.locals.catalogWithTables = catalogWithTables; next(); } );