-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.coffee
116 lines (102 loc) · 2.86 KB
/
index.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
http = require 'http'
url = require 'url'
qs = require 'querystring'
util = require 'util'
module.exports = class Elastics
@normalizeFilters: (filters) ->
return filters unless util.isArray filters
if 1 < filters.length
and: filters: filters
else
filters[0]
@normalizeQuery: (query, filters) ->
filter = @normalizeFilters filters
query ||= match_all: {}
if filter
filtered:
query: query
filter: filter
else
query
@termsQuery: (field, val, options = {}) ->
if util.isArray val
result = terms: {}
result.terms[field] = val
result.terms.execution = options.execution if options.execution
else
result = term: {}
result.term[field] = val
result
constructor: (@defaults = {}) ->
@defaults.host ||= 'localhost'
@defaults.port ||= 9200
setIndex: (index, type) ->
@defaults.index = index || null
@defaults.type = type || null
@
setType: (type) ->
@defaults.type = type
@
generatePath: (params) ->
str = ''
index = params.index || @defaults.index
type = params.type || @defaults.type
if index?
str += '/' + index
str += '/' + type if type?
path = if params.id? then params.id else params.path
str += '/' + path if path?
str += '?' + qs.stringify params.query if params.query
str
request: (params, callback) ->
req = http.request
host: params.host || @defaults.host
port: params.port || @defaults.port
method: params.method || 'GET'
path: @generatePath params
headers: 'Content-Type': 'application/json'
agent: @defaults.agent
(res) ->
res_data = ''
res.on 'data', (chunk) ->
res_data += chunk
res.on 'error', (err) ->
callback? err
res.on 'end', ->
unless 300 > @statusCode
return callback? new Error res_data
try
obj = JSON.parse res_data
catch err
return callback? err
callback? null, obj
.on 'error', (err) ->
callback? err
if params.data
req.write JSON.stringify params.data
req.end()
# shortcuts
['PUT', 'POST', 'DELETE'].forEach (method) =>
@::[method.toLowerCase()] = (params, callback) ->
params.method = method
@request params, callback
set: (id, data, callback) ->
@put
id: id
data: data
callback
get: (params, callback) ->
params = id: params unless typeof params is 'object'
params.method = 'GET'
@request params, callback
putMapping: (params, callback) ->
params.path = '_mapping'
@put params, callback
search: (params, callback) ->
params.path = '_search'
@post params, callback
index: (params, callback) ->
if params.id
@put params, callback
else
@post params, callback