Search code examples
node.jstypescriptneo4jdrivine

drivine how to set neo4j connection info without environment variables


In the Drivine neo4j driver, how do I set the application to connect to a specified database in code without setting the environment variables.


Solution

  • To register a new connection dynamically:

    Ensure that the following code has been called first:

    DatabaseRegistry.getInstance().builder()
            .withType(DatabaseType.NEO4J)
            .host(host)
            .userName(userName)
            .password(password)
            .databaseName(dbName) // On Neo4j version 4 we can have multiple DBs
            .port(nonStandardPortIfNeeded)
            .register('MY_UNIQUE_NAME');
    

    Note: Rather than using the DatabaseRegistry as a singleton, you can of course also @Inject() it.

    The code above could go in the body of the constructor below, or anywhere, as long as it is called before the persistence manager is obtained from the factory.

    Obtain Persistence Manager From Factory:

    Once a database has been registered, you can obtain a persistence manager for that db, like this:

    @Injectable()
    export class PersonRepository {
    
        readonly persistenceManager: PersistenceManager;
    
        constructor(@Inject() readonly factory: PersistenceManagerFactory) {
        }
    
        async someOperation(): Promise<void> {
            const persistenceManager = this.factory.get('MY_UNIQUE_NAME')
            //Now use persistence manager 
        }
    
    }
    

    Details:

    • In the first case we use the DatabaseRegistry's builder to build or resolve a named ConnectionProvider with the specified properties.
    • In the second case we use the PersistenceManagerFactory to obtain a PersistenceManager for the named connection details. The connection provider takes care of returning a connection (possibly pooled depending on platform) for that database in the most expedient manner.

    And that's it. By the way, Drivine works for other graph databases as well.