0

I am trying to merge server and database configuration using the ServerConfig block in ratpack.groovy but postgresConfig is null when trying to create the datasource.

PostgresConfig.groovy

@Compile Static
class PostgresConfig {
    String user
    String password
    String serverName
    String databaseName
    Integer portNumber
}

PostgresModule.groovy

@CompileStatic
class PostgresModule extends ConfigurableModule<PostgresConfig> {
    @Override
    protected void configure() {
    }

    @Provides
    DataSource dataSource(final PostgresConfig config) {
        createDataSource(config)
    }

    protected DataSource createDataSource(final PostgresConfig config) {
        new PgSimpleDataSource(
            user:         config.user,
            password:     config.password,
            serverName:   config.serverName,
            databaseName: config.databaseName,
            portNumber:   config.portNumber
        )
    }
}

ratpack.groovy

ratpack {
    serverConfig {
        props([
            'postgres.user':         'username',
            'postgres.password':     'password',
            'postgres.serverName':   'localhost',
            'postgres.databaseName': 'postgres',
            'postgres.portNumber':   5432
        ] as Map<String, String>)
        yaml "config.yaml"
        env()
        sysProps()
        require("/postgres", PostgresConfig)
    }
    bindings {
        PostgresConfig postgresConfig
        module HikariModule, { HikariConfig config ->
            config.dataSource = new PostgresModule().dataSource(postgresConfig)
        }
    }
}
James Allman
  • 40,573
  • 11
  • 57
  • 70

1 Answers1

0

In the bindings block you can reference the serverConfig configuration and so get a configured PostgresConfig. In your use case you don't need the require("/postgres", PostgresConfig) statement.

You could make the PostgresModule class not extend ConfigurableModule, because it is not used as a module.

ratpack {
    serverConfig { ... }
    bindings {
        module HikariModule, { HikariConfig config ->
            config.dataSource = new PostgresModule().dataSource(serverConfig.get("/postgres", PostgresConfig)
        }
    }
}
mrhaki
  • 3,512
  • 1
  • 14
  • 8