diff --git a/src/controllers/search.controller.js b/src/controllers/search.controller.js index 7757068..c2990fe 100644 --- a/src/controllers/search.controller.js +++ b/src/controllers/search.controller.js @@ -1,4 +1,5 @@ const Post = require('../model/post') +const User = require('../model/user') const {calcRep} = require('../utils') const steem = require('steem') @@ -80,8 +81,6 @@ exports.search = (req, res) => { }} ) - console.log(JSON.stringify(pipeline)) - try { Post.aggregate(pipeline).exec((err, result) => { if (!err) { @@ -122,3 +121,84 @@ exports.search = (req, res) => { console.log(err) } } + +// Search Users + +exports.search_users = (req, res) => { + const getUsers = new Promise(function (resolve, reject) { + const {searchText, pageNumber, order, limit} = req.body + const skipCount = limit * (pageNumber - 1) + let sortMethod = {} + // Set sort method based on request + switch (order.toLowerCase()) { + case 'oldest': + sortMethod = { + _id: 1 + } + break + case 'newest': + sortMethod = { + _id: -1 + } + break + } + // Set pipeline, left in own array for easier optional fields in the future + let pipeline = [ + {$match: {username: { $regex: searchText }}}, + {$match: {deleted: false}}, + {$match: {disabled: false}} + ] + // Add facet for search result data, pagination & user count + pipeline.push( + { '$facet': { + 'search_data': [ + {'$sort': sortMethod}, + {'$skip': skipCount}, + {'$limit': limit} + ], + 'post_count': [ + { $count: 'count' } + ] + }} + ) + // Search users table and gather data from steem blockchain about user + User.aggregate(pipeline).exec((err, result) => { + if (!err) { + let pageCount = 0 + // If results calculate the number of pages + if (result[0].post_count[0]) { + pageCount = Math.ceil(result[0].post_count[0].count / limit) + } + let combinedResults = [] + result[0].search_data.forEach(singleUser => { + steem.api.getAccounts([singleUser.username], function (err, steemUser) { + if (!err) { + singleUser.rep = calcRep(singleUser.username) + const mergedResults = {...singleUser, ...steemUser[0]} + combinedResults.push(mergedResults) + } else { + reject(err) + } if (combinedResults.length === result[0].search_data.length) { + resolve({ + searchResults: combinedResults, + pageCount: pageCount + }) + } + }) + }) + } else { + reject(err) + } + }) + }) + // Upon promise being resolved, send list of users back to client + getUsers + .then(function (userList) { + res.send( + userList + ) + }).catch(function (err) { + console.log(err) + res.status(500) + }) +} diff --git a/src/routes/search.route.js b/src/routes/search.route.js index 18aa025..65119f8 100644 --- a/src/routes/search.route.js +++ b/src/routes/search.route.js @@ -7,7 +7,8 @@ const searchController = require('../controllers/search.controller') // Routes -router.post('/search_posts/:limit?', searchController.search) +router.post('/search_posts/', searchController.search) +router.post('/search_users/', searchController.search_users) // Export