-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.ts
executable file
·87 lines (73 loc) · 1.93 KB
/
db.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
import neo4j from "neo4j-driver"
export const {
NEO4J_URL = "bolt://neo4j",
NEO4J_USERNAME = "neo4j",
NEO4J_PASSWORD = "neo4j",
} = process.env
const auth = neo4j.auth.basic(NEO4J_USERNAME, NEO4J_PASSWORD)
const options = {
v1: {},
v2: { disableLosslessIntegers: true },
}
export const drivers = {
v1: neo4j.driver(NEO4J_URL, auth, options.v1),
v2: neo4j.driver(NEO4J_URL, auth, options.v2),
}
let connected = false
const get_connection_status = async () => {
const session = drivers.v2.session()
try {
console.log(`[Neo4J] Testing connection...`)
await session.run("RETURN 1")
console.log(`[Neo4J] Connection successful`)
return true
} catch (e) {
console.log(`[Neo4J] Connection failed`)
return false
} finally {
session.close()
}
}
const set_ids = async () => {
const id_setting_query = `
MATCH (g:Group)
WHERE g._id IS NULL
SET g._id = toString(id(g))
RETURN COUNT(g) as count
`
const session = drivers.v2.session()
try {
const { records } = await session.run(id_setting_query)
const count = records[0].get("count")
console.log(`[Neo4J] Formatted new ID for ${count} groups`)
} catch (e) {
throw e
} finally {
session.close()
}
}
const create_constraints = async () => {
const session = drivers.v2.session()
try {
await session.run(
`CREATE CONSTRAINT IF NOT EXISTS FOR (g:Group) REQUIRE g._id IS UNIQUE`
)
console.log(`[Neo4J] Created constraints`)
} catch (error) {
throw error
} finally {
session.close()
}
}
export const init = async () => {
if (await get_connection_status()) {
connected = true
console.log("[Neo4J] Initializing DB...")
await set_ids()
await create_constraints()
console.log("[Neo4J] DB initialized")
} else {
setTimeout(init, 10000)
}
}
export const getConnected = () => connected