|
| 1 | +const _ = require('lodash'); |
| 2 | +const moment = require('moment'); |
| 3 | + |
| 4 | +const AttributionEntity = require('../model/attribution-entity'); |
| 5 | +const elasticsearch = require('../util/elasticsearch'); |
| 6 | + |
| 7 | +const getSuggestedApps = async limit => { |
| 8 | + const response = await elasticsearch.getClient().search({ |
| 9 | + index: 'fills', |
| 10 | + body: { |
| 11 | + aggs: { |
| 12 | + attributions: { |
| 13 | + nested: { path: 'attributions' }, |
| 14 | + aggs: { |
| 15 | + apps: { |
| 16 | + filter: { |
| 17 | + terms: { |
| 18 | + 'attributions.type': [0, 1], |
| 19 | + }, |
| 20 | + }, |
| 21 | + aggs: { |
| 22 | + stats_by_app: { |
| 23 | + terms: { |
| 24 | + field: 'attributions.id', |
| 25 | + order: { 'attribution>tradeVolume': 'desc' }, |
| 26 | + size: limit, |
| 27 | + }, |
| 28 | + aggs: { |
| 29 | + attribution: { |
| 30 | + reverse_nested: {}, |
| 31 | + aggs: { |
| 32 | + tradeVolume: { |
| 33 | + sum: { |
| 34 | + field: 'tradeVolume', |
| 35 | + }, |
| 36 | + }, |
| 37 | + }, |
| 38 | + }, |
| 39 | + }, |
| 40 | + }, |
| 41 | + }, |
| 42 | + }, |
| 43 | + }, |
| 44 | + }, |
| 45 | + }, |
| 46 | + size: 0, |
| 47 | + query: { |
| 48 | + range: { |
| 49 | + date: { |
| 50 | + gte: moment() |
| 51 | + .subtract(30, 'days') |
| 52 | + .toDate(), |
| 53 | + }, |
| 54 | + }, |
| 55 | + }, |
| 56 | + }, |
| 57 | + }); |
| 58 | + |
| 59 | + const appBuckets = |
| 60 | + response.body.aggregations.attributions.apps.stats_by_app.buckets; |
| 61 | + const appIds = appBuckets.map(bucket => bucket.key); |
| 62 | + const apps = await AttributionEntity.find({ _id: { $in: appIds } }).lean(); |
| 63 | + |
| 64 | + return appBuckets.map(bucket => { |
| 65 | + const app = apps.find(a => a._id === bucket.key); |
| 66 | + |
| 67 | + return { |
| 68 | + id: app._id, |
| 69 | + logoUrl: _.get(app, 'logoUrl', null), |
| 70 | + name: app.name, |
| 71 | + urlSlug: app.urlSlug, |
| 72 | + websiteUrl: _.get(app, 'websiteUrl', null), |
| 73 | + }; |
| 74 | + }); |
| 75 | +}; |
| 76 | + |
| 77 | +function escapeRegex(text) { |
| 78 | + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); |
| 79 | +} |
| 80 | + |
| 81 | +const searchApps = async (query, options) => { |
| 82 | + if (query === '' || query === null) { |
| 83 | + const suggestedApps = await getSuggestedApps(options.limit); |
| 84 | + |
| 85 | + return suggestedApps; |
| 86 | + } |
| 87 | + |
| 88 | + const matchingApps = await AttributionEntity.find({ |
| 89 | + name: new RegExp(escapeRegex(query), 'ig'), |
| 90 | + }) |
| 91 | + .sort({ name: 1 }) |
| 92 | + .limit(options.limit) |
| 93 | + .lean(); |
| 94 | + |
| 95 | + return matchingApps.map(app => ({ |
| 96 | + id: app._id, |
| 97 | + logoUrl: _.get(app, 'logoUrl', null), |
| 98 | + name: app.name, |
| 99 | + urlSlug: app.urlSlug, |
| 100 | + websiteUrl: _.get(app, 'websiteUrl', null), |
| 101 | + })); |
| 102 | +}; |
| 103 | + |
| 104 | +module.exports = searchApps; |
0 commit comments