var search = require('./search') var snippet = require('./snippet') var db = require('../db') module.exports = { search: function (req, res, next) { res.search = search.search(req.query.query, req.query.start, req.query.limit) if (! res.search) { res.sendStatus(400) return } next() }, getThreads: function (req, res, next){ var thread_ids = res.search.thread_ids; if (! thread_ids || ! thread_ids.length) { res.search.threads = [] return next() } db.getThreadsById(thread_ids).then(function(threads){ threads.forEach((thread) => { var flag_id = thread.get('flagged') if (flag_id) { res.search.file_ids.push(flag_id) } }) res.search.threads = threads next() }) }, getComments: function (req, res, next){ var comment_ids = res.search.comment_ids; if (! comment_ids || ! comment_ids.length) { res.search.comments = [] return next() } db.getCommentsById(comment_ids).then(function(comments){ var terms = res.search.meta.terms comments.forEach(function(comment){ const snip = snippet(comment.get('comment').toString(), terms) comment.set('comment', snip) }) res.search.comments = comments next() }) }, getFiles: function (req, res, next){ var file_ids = res.search.file_ids if (! file_ids || ! file_ids.length) { res.search.files = [] return next() } db.getFilesById(file_ids).then(function(files){ res.search.files = files next() }) }, logQuery: function(req, res, next) { // req.search.query, req.search.count next() }, success: function(req, res, next){ var terms = res.search.meta.terms var threads = {}, comments = {}, files = {} res.search.threads.forEach((t) => { threads[t.id] = t }) res.search.comments.forEach((t) => { comments[t.id] = t }) res.search.files.forEach((t) => { files[t.id] = t }) var results = res.search.results.map((r) => { var m = {} m.thread = threads[r.thread] m.comment = comments[r.comment] m.file = files[r.file] m.count = r.count m.strength = r.strength if (m.thread) { var flagged = m.thread.get('flagged') if (flagged) { m.thread.set('flagged', files[flagged]) } var allowed = m.thread.get('allowed') if (allowed) { m.thread.set('allowed', allowed.toString().split(" ")) } var display = m.thread.get('display') if (display) { m.thread.set('display', display.toString().split(" ")) } } return m }) res.json({ meta: res.search.meta, results: results, }) }, }