In the Drivine neo4j driver, how do I set the application to connect to a specified database in code without setting the environment variables.
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:
DatabaseRegistry
's builder to build or resolve a named ConnectionProvider
with the specified properties.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.