File size: 6,778 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import neo4j, { Driver, Session } from 'neo4j-driver';

export interface GraphNode {
    id: string;
    labels: string[];
    properties: Record<string, any>;
}

export interface GraphRelationship {
    id: string;
    type: string;
    startNodeId: string;
    endNodeId: string;
    properties: Record<string, any>;
}

export class Neo4jService {
    private driver: Driver | null = null;
    private uri: string;
    private username: string;
    private password: string;

    constructor() {
        this.uri = process.env.NEO4J_URI || 'bolt://localhost:7687';
        // Support both NEO4J_USER and NEO4J_USERNAME for compatibility
        this.username = process.env.NEO4J_USER || process.env.NEO4J_USERNAME || 'neo4j';
        this.password = process.env.NEO4J_PASSWORD || 'password';
    }

    async connect(): Promise<void> {
        try {
            this.driver = neo4j.driver(
                this.uri,
                neo4j.auth.basic(this.username, this.password),
                {
                    maxConnectionPoolSize: 50,
                    connectionAcquisitionTimeout: 60000,
                }
            );
            await this.driver.verifyConnectivity();
            console.log('✅ Neo4j connected successfully', this.uri);
        } catch (error) {
            console.error('❌ Failed to connect to Neo4j', error);
            throw error;
        }
    }

    async disconnect(): Promise<void> {
        if (this.driver) {
            await this.driver.close();
            this.driver = null;
            console.log('Neo4j disconnected');
        }
    }

    async close(): Promise<void> {
        await this.disconnect();
    }

    private getSession(): Session {
        if (!this.driver) {
            throw new Error('Neo4j driver not initialized. Call connect() first.');
        }
        return this.driver.session();
    }

    async createNode(labels: string[], properties: Record<string, any>): Promise<GraphNode> {
        const session = this.getSession();
        try {
            const labelsStr = labels.map(l => `:${l}`).join('');
            const result = await session.run(
                `CREATE (n${labelsStr} $properties) RETURN n`,
                { properties }
            );
            const node = result.records[0].get('n');
            return {
                id: node.elementId,
                labels: node.labels,
                properties: node.properties,
            };
        } finally {
            await session.close();
        }
    }

    async createRelationship(
        startNodeId: string,
        endNodeId: string,
        type: string,
        properties: Record<string, any> = {}
    ): Promise<GraphRelationship> {
        const session = this.getSession();
        try {
            // Use elementId lookup instead of id()
            const result = await session.run(
                `MATCH (a), (b)
         WHERE elementId(a) = $startId AND elementId(b) = $endId
         CREATE (a)-[r:${type} $properties]->(b)
         RETURN r`,
                { startId: startNodeId, endId: endNodeId, properties }
            );
            const rel = result.records[0].get('r');
            return {
                id: rel.elementId,
                type: rel.type,
                startNodeId: rel.startNodeElementId,
                endNodeId: rel.endNodeElementId,
                properties: rel.properties,
            };
        } finally {
            await session.close();
        }
    }

    async findNodes(label: string, properties: Record<string, any> = {}): Promise<GraphNode[]> {
        const session = this.getSession();
        try {
            const whereClause = Object.keys(properties).length > 0
                ? 'WHERE ' + Object.keys(properties).map(k => `n.${k} = $${k}`).join(' AND ')
                : '';
            const result = await session.run(
                `MATCH (n:${label}) ${whereClause} RETURN n`,
                properties
            );
            return result.records.map(record => {
                const node = record.get('n');
                return {
                    id: node.elementId,
                    labels: node.labels,
                    properties: node.properties,
                };
            });
        } finally {
            await session.close();
        }
    }

    async runQuery(query: string, parameters: Record<string, any> = {}): Promise<any[]> {
        const session = this.getSession();
        try {
            const result = await session.run(query, parameters);
            return result.records.map(record => record.toObject());
        } finally {
            await session.close();
        }
    }

    async getNodeById(nodeId: string): Promise<GraphNode | null> {
        const session = this.getSession();
        try {
            const result = await session.run(
                'MATCH (n) WHERE elementId(n) = $id RETURN n',
                { id: nodeId }
            );
            if (result.records.length === 0) return null;
            const node = result.records[0].get('n');
            return {
                id: node.elementId,
                labels: node.labels,
                properties: node.properties,
            };
        } finally {
            await session.close();
        }
    }

    async deleteNode(nodeId: string): Promise<void> {
        const session = this.getSession();
        try {
            await session.run(
                'MATCH (n) WHERE elementId(n) = $id DETACH DELETE n',
                { id: nodeId }
            );
        } finally {
            await session.close();
        }
    }

    async getNodeRelationships(nodeId: string): Promise<GraphRelationship[]> {
        const session = this.getSession();
        try {
            const result = await session.run(
                `MATCH (n)-[r]-(m) 
         WHERE elementId(n) = $id 
         RETURN r`,
                { id: nodeId }
            );
            return result.records.map(record => {
                const rel = record.get('r');
                return {
                    id: rel.elementId,
                    type: rel.type,
                    startNodeId: rel.startNodeElementId,
                    endNodeId: rel.endNodeElementId,
                    properties: rel.properties,
                };
            });
        } finally {
            await session.close();
        }
    }

    async healthCheck(): Promise<boolean> {
        try {
            if (!this.driver) return false;
            await this.driver.verifyConnectivity();
            return true;
        } catch (error) {
            console.error('Neo4j health check failed', error);
            return false;
        }
    }
}

export const neo4jService = new Neo4jService();