-
Notifications
You must be signed in to change notification settings - Fork 71
/
index.js
524 lines (456 loc) · 13.3 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import fs from 'fs';
import path from 'path';
import neo4j from 'neo4j-driver';
import Factory from './Factory';
import Model from './Model';
import ModelMap from './ModelMap';
import Schema from './Schema';
import TransactionError from './TransactionError';
import Builder from './Query/Builder';
import Collection from './Collection';
export default class Neode {
/**
* Constructor
*
* @param {String} connection_string
* @param {String} username
* @param {String} password
* @param {Bool} enterprise
* @param {String} database
* @param {Object} config
* @return {Neode}
*/
constructor(connection_string, username, password, enterprise = false, database = undefined, config = {}) {
const auth = username && password ? neo4j.auth.basic(username, password) : null;
this.driver = new neo4j.driver(connection_string, auth, config);
this.models = new ModelMap(this);
this.schema = new Schema(this);
this.factory = new Factory(this);
this.database = database;
this.setEnterprise(enterprise);
}
/**
* @static
* Generate Neode instance using .env configuration
*
* @return {Neode}
*/
static fromEnv() {
require('dotenv').config();
const connection_string = `${process.env.NEO4J_PROTOCOL}://${process.env.NEO4J_HOST}:${process.env.NEO4J_PORT}`;
const username = process.env.NEO4J_USERNAME;
const password = process.env.NEO4J_PASSWORD;
const enterprise = process.env.NEO4J_ENTERPRISE === 'true';
// Multi-database
const database = process.env.NEO4J_DATABASE || 'neo4j';
// Build additional config
const config = {};
const settings = {
NEO4J_ENCRYPTION: 'encrypted',
NEO4J_TRUST: 'trust',
NEO4J_TRUSTED_CERTIFICATES: 'trustedCertificates',
NEO4J_KNOWN_HOSTS: 'knownHosts',
NEO4J_MAX_CONNECTION_POOLSIZE: 'maxConnectionPoolSize',
NEO4J_MAX_TRANSACTION_RETRY_TIME: 'maxTransactionRetryTime',
NEO4J_LOAD_BALANCING_STRATEGY: 'loadBalancingStrategy',
NEO4J_MAX_CONNECTION_LIFETIME: 'maxConnectionLifetime',
NEO4J_CONNECTION_TIMEOUT: 'connectionTimeout',
NEO4J_DISABLE_LOSSLESS_INTEGERS: 'disableLosslessIntegers',
NEO4J_LOGGING_LEVEL: 'logging',
};
Object.keys(settings).forEach(setting => {
if ( process.env.hasOwnProperty(setting) ) {
const key = settings[ setting ];
let value = process.env[ setting ];
if ( key == "trustedCertificates" ) {
value = value.split(',');
}
else if ( key == "disableLosslessIntegers" ) {
value = value === 'true';
}
config[ key ] = value;
}
});
return new Neode(connection_string, username, password, enterprise, database, config);
}
/**
* Define multiple models
*
* @param {Object} models Map of models with their schema. ie {Movie: {...}}
* @return {Neode}
*/
with(models) {
Object.keys(models).forEach(model => {
this.model(model, models[ model ]);
});
return this;
}
/**
* Scan a directory for Models
*
* @param {String} directory Directory to scan
* @return {Neode}
*/
withDirectory(directory) {
const files = fs.readdirSync(directory);
files.filter(file => path.extname(file).toLowerCase() === '.js')
.forEach(file => {
const model = file.replace('.js', '');
const path = directory +'/'+ file;
const schema = require("" + path);
return this.model(model, schema);
});
return this;
}
/**
* Set the default database for all future connections
*
* @param {String} database
*/
setDatabase(database) {
this.database = database;
}
/**
* Set Enterprise Mode
*
* @param {Bool} enterprise
*/
setEnterprise(enterprise) {
this._enterprise = enterprise;
}
/**
* Are we running in enterprise mode?
*
* @return {Bool}
*/
enterprise() {
return this._enterprise;
}
/**
* Define a new Model
*
* @param {String} name
* @param {Object} schema
* @return {Model}
*/
model(name, schema) {
if ( schema instanceof Object) {
const model = new Model(this, name, schema);
this.models.set(name, model);
}
if ( !this.models.has(name) ) {
const defined = this.models.keys();
let message = `Couldn't find a definition for "${name}".`;
if ( defined.length == 0 ) {
message += ' It looks like no models have been defined.';
}
else {
message += ` The models currently defined are [${ defined.join(', ') }]`;
}
throw new Error(message);
}
return this.models.get(name);
}
/**
* Extend a model with extra configuration
*
* @param {String} name Original Model to clone
* @param {String} as New Model name
* @param {Object} using Schema changes
* @return {Model}
*/
extend(model, as, using) {
return this.models.extend(model, as, using);
}
/**
* Create a new Node of a type
*
* @param {String} model
* @param {Object} properties
* @return {Node}
*/
create(model, properties) {
return this.models.get(model).create(properties);
}
/**
* Merge a node based on the defined indexes
*
* @param {Object} properties
* @return {Promise}
*/
merge(model, properties) {
return this.model(model).merge(properties);
}
/**
* Merge a node based on the supplied properties
*
* @param {Object} match Specific properties to merge on
* @param {Object} set Properties to set
* @return {Promise}
*/
mergeOn(model, match, set) {
return this.model(model).mergeOn(match, set);
}
/**
* Delete a Node from the graph
*
* @param {Node} node
* @return {Promise}
*/
delete(node) {
return node.delete();
}
/**
* Delete all node labels
*
* @param {String} label
* @return {Promise}
*/
deleteAll(model) {
return this.models.get(model).deleteAll();
}
/**
* Relate two nodes based on the type
*
* @param {Node} from Origin node
* @param {Node} to Target node
* @param {String} type Type of Relationship definition
* @param {Object} properties Properties to set against the relationships
* @param {Boolean} force_create Force the creation a new relationship? If false, the relationship will be merged
* @return {Promise}
*/
relate(from, to, type, properties, force_create = false) {
return from.relateTo(to, type, properties, force_create);
}
/**
* Run an explicitly defined Read query
*
* @param {String} query
* @param {Object} params
* @return {Promise}
*/
readCypher(query, params) {
const session = this.readSession();
return this.cypher(query, params, session);
}
/**
* Run an explicitly defined Write query
*
* @param {String} query
* @param {Object} params
* @return {Promise}
*/
writeCypher(query, params) {
const session = this.writeSession();
return this.cypher(query, params, session);
}
/**
* Run a Cypher query
*
* @param {String} query
* @param {Object} params
* @return {Promise}
*/
cypher(query, params, session = false) {
// If single run, open a new session
const single = !session;
if ( single ) {
session = this.session();
}
return session.run(query, params)
.then(res => {
if ( single ) {
session.close();
}
return res;
})
.catch(err => {
if ( single ) {
session.close();
}
err.query = query;
err.params = params;
throw err;
});
}
/**
* Create a new Session in the Neo4j Driver.
*
* @param {String} database
* @return {Session}
*/
session(database = this.database) {
return this.readSession(database);
}
/**
* Create an explicit Read Session
*
* @param {String} database
* @return {Session}
*/
readSession(database = this.database) {
return this.driver.session({
database,
defaultAccessMode: neo4j.session.READ,
});
}
/**
* Create an explicit Write Session
*
* @param {String} database
* @return {Session}
*/
writeSession(database = this.database) {
return this.driver.session({
database,
defaultAccessMode: neo4j.session.WRITE,
});
}
/**
* Create a new Transaction
*
* @return {Transaction}
*/
transaction(mode = neo4j.WRITE, database = this.database) {
const session = this.driver.session(database);
const tx = session.beginTransaction(mode);
// Create an 'end' function to commit & close the session
// TODO: Clean up
tx.success = () => {
return tx.commit()
.then(() => {
session.close();
});
};
return tx;
}
/**
* Run a batch of queries within a transaction
*
* @type {Array}
* @return {Promise}
*/
batch(queries) {
const tx = this.transaction();
const output = [];
const errors = [];
return Promise.all(queries.map(query => {
const params = typeof query == 'object' ? query.params : {};
query = typeof query == 'object' ? query.query : query;
try {
return tx.run(query, params)
.then(res => {
output.push(res);
})
.catch(error => {
errors.push({query, params, error});
});
}
catch (error) {
errors.push({query, params, error});
}
}))
.then(() => {
if (errors.length) {
tx.rollback();
const error = new TransactionError(errors);
throw error;
}
return tx.success()
.then(() => {
return output;
});
});
}
/**
* Close Driver
*
* @return {void}
*/
close() {
this.driver.close();
}
/**
* Return a new Query Builder
*
* @return {Builder}
*/
query() {
return new Builder(this);
}
/**
* Get a collection of nodes`
*
* @param {String} label
* @param {Object} properties
* @param {String|Array|Object} order
* @param {Int} limit
* @param {Int} skip
* @return {Promise}
*/
all(label, properties, order, limit, skip) {
return this.models.get(label).all(properties, order, limit, skip);
}
/**
* Find a Node by it's label and primary key
*
* @param {String} label
* @param {mixed} id
* @return {Promise}
*/
find(label, id) {
return this.models.get(label).find(id);
}
/**
* Find a Node by it's internal node ID
*
* @param {String} model
* @param {int} id
* @return {Promise}
*/
findById(label, id) {
return this.models.get(label).findById(id);
}
/**
* Find a Node by properties
*
* @param {String} label
* @param {mixed} key Either a string for the property name or an object of values
* @param {mixed} value Value
* @return {Promise}
*/
first(label, key, value) {
return this.models.get(label).first(key, value);
}
/**
* Hydrate a set of nodes and return a Collection
*
* @param {Object} res Neo4j result set
* @param {String} alias Alias of node to pluck
* @param {Definition|null} definition Force Definition
* @return {Collection}
*/
hydrate(res, alias, definition) {
return this.factory.hydrate(res, alias, definition);
}
/**
* Hydrate the first record in a result set
*
* @param {Object} res Neo4j Result
* @param {String} alias Alias of Node to pluck
* @return {Node}
*/
hydrateFirst(res, alias, definition) {
return this.factory.hydrateFirst(res, alias, definition);
}
/**
* Turn an array into a Collection
*
* @param {Array} array An array
* @return {Collection}
*/
toCollection(array) {
return new Collection(this, array);
}
}
module.exports = Neode;