-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.js
180 lines (149 loc) · 4.86 KB
/
index.js
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
'use strict';
var logger = require('./lib/logger'),
Client = require('./lib/client'),
Schema = require('./lib/schema'),
errors = require('./lib/errors'),
pluralize = require('pluralize'),
utils = require('./lib/utils'),
MissingArgumentError = errors.MissingArgumentError,
ConnectionError = errors.ConnectionError,
Model = require('./lib/model'),
defaultMethods = require('./lib/default-methods'),
defaultMappings = require('./default-mappings'),
_ = require('lodash'),
Promise = require('bluebird');
logger.transports.console.silent = (process.env.NODE_ENV !== 'development');
var db = {
host: 'localhost:9200',
index: '',
logging: process.env.NODE_ENV === 'development',
client: {},
models: {}
};
var CONNECTED = false;
var mappingQueue = [];
var syncMapping = true;
var handleMappingQueue = function(){
if(!mappingQueue.length || syncMapping == false) return Promise.resolve();
return Promise.map(mappingQueue , function(v){
return db.client.indices.putMapping({
index: db.index,
type: v.type,
ignore_conflicts: true,
body:v.mapping
});
});
};
function connect(options){
if(isConnected()) return Promise.resolve();
// can pass just the index name, or a client configuration object.
if(_.isString(options)){
db.index = options;
}else if(_.isObject(options)){
if(!options.index) return Promise.reject(new MissingArgumentError('options.index'));
if(options.hasOwnProperty('syncMapping')){
syncMapping = options.syncMapping;
delete options.syncMapping;
}
db = _.assign(db, options);
}else{
return Promise.reject(new MissingArgumentError('options'));
}
module.exports.client = db.client = Client.makeClient(db);
return db.client.indices.exists({index: db.index}).then(function(result){
//No error - connected
CONNECTED = true;
if(result){
return handleMappingQueue();
}else{
// if the index doesn't exist, then create it.
return createIndex(db.index).then(handleMappingQueue);
}
})
.then(function(results){
return Promise.resolve();
});
}
function isConnected(){
return CONNECTED;
}
function status(type){
if(!isConnected()) return Promise.reject(new ConnectionError(db.host));
var args = {index: db.index};
if(type) args.type = type;
return db.client.indices.status(args);
}
function createIndex(index, mappings){
if(!index) return Promise.reject(new MissingArgumentError('index'));
if(!isConnected()) return Promise.reject(new ConnectionError(db.host));
return db.client.indices.create({
index: index,
body: mappings || defaultMappings
});
}
function removeIndex(index){
if(!index) return Promise.reject(new MissingArgumentError('index'));
if(!isConnected()) return Promise.reject(new ConnectionError(db.host));
return db.client.indices.delete({index: index}).catch(function(){});
}
function model(modelName, schema){
if(!modelName) throw new MissingArgumentError('modelName');
if(schema && !(schema instanceof Schema)) throw new errors.ElasticsearchError('Invalid schema for "'+modelName+'".');
if(db.models[modelName]){
// don't overwrite schemas on secondary calls.
if(schema && _.isEmpty(db.models[modelName].model.schema)){
db.models[modelName].model.schema = schema;
}
// return model from cache if it exists.
return db.models[modelName];
}
// create a neweable function object.
function modelInstance(data){
var self = this;
// Add any user supplied schema instance methods.
if(schema){
_.assign(self, schema.methods);
}
Model.call(self, data);
}
utils.inherits(modelInstance, Model);
// add crud/query static functions.
_.assign(modelInstance, defaultMethods);
modelInstance.db = db;
modelInstance.model = {
type: pluralize(modelName).toLowerCase(),
name: modelName,
constructor: modelInstance
};
if(schema) {
modelInstance.model.schema = schema;
// Add any user supplied schema static methods.
_.assign(modelInstance, schema.statics);
// User can provide their own type name, default is pluralized.
if(schema.options.type) modelInstance.model.type = schema.options.type;
// Update the mapping asynchronously.
var mapping = {};
mapping[modelInstance.model.type] = schema.toMapping();
mappingQueue.push({type: modelInstance.model.type, mapping: mapping});
// If we're already connected process the mapping queue.
if(isConnected()){
handleMappingQueue();
}
}
return db.models[modelName] = modelInstance;
}
function stats(){
if(!isConnected()) return Promise.reject(new ConnectionError(db.host));
return db.client.indices.stats({index:db.index});
}
module.exports = {
client: db.client,
connect: connect,
isConnected: isConnected,
status: status,
stats: stats,
removeIndex: removeIndex,
createIndex: createIndex,
model: model,
Schema: Schema
};