1 | const api = require('./api');
|
2 | const { isEmpty, isNumber } = require('../utils');
|
3 |
|
4 | const Search = class Search {
|
5 | constructor() {
|
6 | this.query_hash = {
|
7 | sort_by: [],
|
8 | aggregate: [],
|
9 | with_field: [],
|
10 | };
|
11 | }
|
12 |
|
13 | static instance() {
|
14 | return new Search();
|
15 | }
|
16 |
|
17 | static expression(value) {
|
18 | return this.instance().expression(value);
|
19 | }
|
20 |
|
21 | static max_results(value) {
|
22 | return this.instance().max_results(value);
|
23 | }
|
24 |
|
25 | static next_cursor(value) {
|
26 | return this.instance().next_cursor(value);
|
27 | }
|
28 |
|
29 | static aggregate(value) {
|
30 | return this.instance().aggregate(value);
|
31 | }
|
32 |
|
33 | static with_field(value) {
|
34 | return this.instance().with_field(value);
|
35 | }
|
36 |
|
37 | static sort_by(field_name, dir = 'asc') {
|
38 | return this.instance().sort_by(field_name, dir);
|
39 | }
|
40 |
|
41 | expression(value) {
|
42 | this.query_hash.expression = value;
|
43 | return this;
|
44 | }
|
45 |
|
46 | max_results(value) {
|
47 | this.query_hash.max_results = value;
|
48 | return this;
|
49 | }
|
50 |
|
51 | next_cursor(value) {
|
52 | this.query_hash.next_cursor = value;
|
53 | return this;
|
54 | }
|
55 |
|
56 | aggregate(value) {
|
57 | this.query_hash.aggregate.push(value);
|
58 | return this;
|
59 | }
|
60 |
|
61 | with_field(value) {
|
62 | this.query_hash.with_field.push(value);
|
63 | return this;
|
64 | }
|
65 |
|
66 | sort_by(field_name, dir = "desc") {
|
67 | var sort_bucket;
|
68 | sort_bucket = {};
|
69 | sort_bucket[field_name] = dir;
|
70 | this.query_hash.sort_by.push(sort_bucket);
|
71 | return this;
|
72 | }
|
73 |
|
74 | to_query() {
|
75 | Object.keys(this.query_hash).forEach((k) => {
|
76 | let v = this.query_hash[k];
|
77 | if (!isNumber(v) && isEmpty(v)) {
|
78 | delete this.query_hash[k];
|
79 | }
|
80 | });
|
81 | return this.query_hash;
|
82 | }
|
83 |
|
84 | execute(options, callback) {
|
85 | if (callback === null) {
|
86 | callback = options;
|
87 | }
|
88 | options = options || {};
|
89 | return api.search(this.to_query(), options, callback);
|
90 | }
|
91 | };
|
92 |
|
93 | module.exports = Search;
|