{"size": 1701, "ext": "js", "max_stars_repo_path": "src/routes/search.js", "max_stars_repo_name": "deconst/content-service", "max_stars_repo_stars_event_min_datetime": "2015-03-12T19:58:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T01:46:28.000Z", "max_issues_repo_path": "src/routes/search.js", "max_issues_repo_name": "enterstudio/content-service", "max_issues_repo_issues_event_min_datetime": "2015-03-12T21:28:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T14:08:49.000Z", "max_forks_repo_path": "src/routes/search.js", "max_forks_repo_name": "enterstudio/content-service", "max_forks_repo_forks_event_min_datetime": "2015-03-18T20:29:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T05:11:05.000Z"}
{"max_stars_count": 5, "max_issues_count": 63, "max_forks_count": 11, "avg_line_length": 25.7727272727, "max_line_length": 86, "alphanum_fraction": 0.6419753086}
'use strict';

// Accept full-text search queries

var restify = require('restify');
var storage = require('../storage');

exports.query = function (req, res, next) {
  var q = req.params.q;
  var perPage = req.params.perPage || 10;
  var pageNumber = req.params.pageNumber || 1;
  var categories = req.params.categories;

  if (typeof categories === 'string') {
    categories = [categories];
  }

  var logPayload = {
    query: q,
    perPage,
    pageNumber,
    categories
  };

  if (q === null || q === undefined) {
    req.logger.info('Missing required query parameter', logPayload);
    res.send(new restify.MissingParameterError('q parameter is required'));
    return;
  }

  req.logger.debug('Beginning search', logPayload);

  storage.queryEnvelopes(q, categories, pageNumber, perPage, function (err, results) {
    if (err) {
      req.logger.reportError('Error performing search', err, { payload: logPayload });
      res.send(new restify.InternalServerError('Error performing search'));
      return;
    }

    logPayload.totalResultCount = results.hits.total;
    logPayload.pageResultCount = results.hits.hits.length;

    const doc = results.hits.hits.map(function (each) {
      const transformed = {
        contentID: each._id,
        title: each._source.title
      };

      if (each.highlight && each.highlight.body.length > 0) {
        transformed.excerpt = each.highlight.body[0];
      } else {
        transformed.excerpt = each._source.body.substr(0, 150);
      }

      return transformed;
    });

    res.send(200, {
      total: results.hits.total,
      results: doc
    });
    req.logger.info('Successfully completed search', logPayload);
    next();
  });
};
