1 |
|
2 | (function() {
|
3 | var Search, http;
|
4 |
|
5 | http = require('http');
|
6 |
|
7 | Search = (function() {
|
8 |
|
9 | function Search(host, tenant, port) {
|
10 | this.host = host != null ? host : 'localhost';
|
11 | this.tenant = tenant != null ? tenant : 'bfdocs';
|
12 | this.port = port != null ? port : 9200;
|
13 | }
|
14 |
|
15 | Search.prototype.index = function(manifest, callback) {
|
16 | var c, handler, i, slug, _i, _len, _ref, _results;
|
17 | c = 1 + manifest.slugs.length;
|
18 | handler = function(res) {
|
19 | if (--c === 0 && callback) {
|
20 | return callback();
|
21 | }
|
22 | };
|
23 | this.request('put', manifest.slug, '_home', {
|
24 | body: manifest.homeData
|
25 | }, handler);
|
26 | _ref = manifest.slugs;
|
27 | _results = [];
|
28 | for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
|
29 | slug = _ref[i];
|
30 | if (slug) {
|
31 | _results.push(this.request('put', manifest.slug, slug, {
|
32 | body: manifest.filesData[i]
|
33 | }, handler));
|
34 | } else {
|
35 | _results.push(void 0);
|
36 | }
|
37 | }
|
38 | return _results;
|
39 | };
|
40 |
|
41 | Search.prototype.search = function(manifest, query, callback) {
|
42 | var q;
|
43 | q = {
|
44 | query: {
|
45 | text: {
|
46 | _all: query
|
47 | }
|
48 | }
|
49 | };
|
50 | return this.request('post', manifest.slug, '_search', q, function(res) {
|
51 | var h, slugs, _i, _len, _ref;
|
52 | slugs = [];
|
53 | if (res && res.hits) {
|
54 | _ref = res.hits.hits;
|
55 | for (_i = 0, _len = _ref.length; _i < _len; _i++) {
|
56 | h = _ref[_i];
|
57 | slugs.push(h._id);
|
58 | }
|
59 | }
|
60 | return callback(slugs);
|
61 | });
|
62 | };
|
63 |
|
64 | Search.prototype.request = function(method, type, path, payload, callback) {
|
65 | var options, req;
|
66 | options = {
|
67 | host: this.host,
|
68 | port: this.port,
|
69 | method: method.toUpperCase(),
|
70 | path: this.tenant + '/' + type + '/' + path
|
71 | };
|
72 | req = http.request(options, function(res) {
|
73 | res.setEncoding('utf8');
|
74 | return res.on('data', function(data) {
|
75 | return callback(JSON.parse(data.toString()));
|
76 | });
|
77 | });
|
78 | req.on('error', function(e) {
|
79 | console.log('ERROR: ' + e.message);
|
80 | return callback(false);
|
81 | });
|
82 | req.write(JSON.stringify(payload));
|
83 | return req.end();
|
84 | };
|
85 |
|
86 | return Search;
|
87 |
|
88 | })();
|
89 |
|
90 | module.exports = Search;
|
91 |
|
92 | }).call(this);
|