-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
neo4j.model.service.ts
97 lines (84 loc) · 2.69 KB
/
neo4j.model.service.ts
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
import { Logger } from '@nestjs/common';
import { Neo4jService } from './neo4j.service';
import { Query, SessionOptions } from '../interface';
import { TransactionConfig } from 'neo4j-driver-core/types/session';
import { int } from 'neo4j-driver';
/**
* Helper class to generate model service using Neo4j.
*/
export abstract class Neo4jModelService<T> {
protected abstract readonly neo4jService: Neo4jService;
/**
* Node or Relationship label.
*/
public abstract readonly label: string;
/**
* Override this to use logger.
*/
protected abstract readonly logger: Logger | undefined;
/**
* Override this with property name to generate timestamp on object creation.
*/
protected abstract readonly timestamp: string | undefined;
/**
* Override this to transform object before sending it to Neo4j.
* @param params Neo4j compatible Parameters.
*/
public toNeo4j(params: Partial<T>): Record<string, any> {
let result: Record<string, any> = { ...params };
if (this.timestamp && params && params[this.timestamp]) {
if (this.neo4jService.getConfig().disableLosslessIntegers) {
result[this.timestamp] = params[this.timestamp].getTime();
} else {
result[this.timestamp] = int(params[this.timestamp].getTime());
}
}
return { ...result };
}
/**
* Override this to transform object coming from Neo4j.
* @param record Neo4j results to object.
*/
public fromNeo4j(record: Record<string, any>): T {
let result: Record<string, any> = { ...record };
if (this.timestamp && record && record[this.timestamp]) {
result[this.timestamp] = new Date(Number(result[this.timestamp]));
}
return result as T;
}
/**
* Run cypher constraint for this label in a transaction.
*/
public async runCypherConstraints(): Promise<string[]> {
this.logger?.debug('runCypherConstraints()');
const queries = this.neo4jService.getCypherConstraints(this.label);
const session = this.neo4jService.getSession({ write: true });
try {
const tx = session.beginTransaction();
queries.forEach((query) => {
tx.run(query);
});
await tx.commit();
} finally {
await session.close();
}
return queries;
}
/**
* Run query with debug log if logger is defined and convert results to objects.
*/
protected async _run(
query: Query<T>,
sessionOptions?: SessionOptions,
transactionConfig?: TransactionConfig,
) {
this.logger?.debug('_run', arguments);
const queryResult = await this.neo4jService.run(
query,
sessionOptions,
transactionConfig,
);
this.logger?.debug(queryResult);
return queryResult.records.map((r) => r.toObject());
}
}