Created
October 17, 2017 13:37
-
-
Save DaniilVysotskiy/2c61e4808fd5a60f49efce99a1adad28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fnProfileCatalog = function(req, res, next) { | |
var regionId = getUserRegionId(req); | |
// Filter params | |
var type = req.query.type; | |
var userLimit = parseInt(req.query.perPage); | |
var limit = (!isNaN(userLimit) && userLimit <= perPageMax) ? userLimit : perPageDefault; | |
var page = (!isNaN(parseInt(req.query.page)) ? parseInt(req.query.page) : 1); | |
var offset = (page - 1) * limit; | |
var profilesQ; | |
var profilesOrder = ['id', 'DESC']; | |
// поиск общего количества и айдишников текущей страницы в базе | |
var searchObject = { | |
where: { | |
}, | |
subQuery: false, | |
attributes: ['id'], | |
include: [], | |
limit: limit, | |
offset: offset, | |
order: profilesOrder | |
}; | |
if (type) { | |
searchObject.where.type = type; | |
} | |
// searchObject = isShowProductToUserQ(searchObject, res); | |
profilesQ = Profiles.findAndCountAll({attributes: ['id']}).then(function (profilesIds) { | |
if (profilesIds && profilesIds.rows && profilesIds.rows.length) { | |
return { | |
items: profilesIds.rows.map(function (item) { | |
return parseInt(item.id); | |
}), | |
count: profilesIds.count | |
}; | |
} else { | |
throw new Error('no profiles found by db'); | |
} | |
}).catch(function () { | |
return { | |
items: [], | |
count: 0 | |
}; | |
}); | |
return profilesQ.then(function (items) { | |
// IDs профилей текущей страницы и общее количество профилей по всем фильтрам. | |
var profilesCount = items.count; | |
var ids = items.items; | |
// Данные на отрисовку | |
return db.Promise.props({ | |
profiles: profilesCount ? Profiles.findAll({ | |
where: { | |
id: { | |
$in: ids | |
} | |
}, | |
}) : [] | |
}).then(function(result) { | |
// render template | |
var templateObject = { | |
empty: ((profilesCount) ? false : true), | |
title: 'Основной раздел', | |
profiles: result.profiles.sort(function (a, b) { | |
// сортировка текущей страницы по индексам возвращённых айдишников | |
return ids.indexOf(a.id) - ids.indexOf(b.id); | |
}) | |
}; | |
res.render(templates.catalog, templateObject); | |
return true; | |
}); | |
}).catch(function (error) { | |
if(true) { | |
res.render(templates.catalogEmpty, { | |
title: 'Основной раздел' | |
}); | |
} else { | |
next(error); | |
} | |
}); | |
}; | |
router.get(links.catalog, fnProfileCatalog); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment