with spring boot, lateinit on nullable type #897
-
I'm implementing lateinit in model to use DataLoader in Spring. Refererd this example code, The question is, If the lateinit is EMPTY, the value cannot be null because of "lateinit". What can be a good design for nullable field with dataloader and datafetcher? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Disclaimer: I'm not an expert on dataloader as I haven't used it but below should work. Instead of a fun foo(id: Int, environment: DataFetchingEnvironment): CompletableFuture<String?> {
return environment.getDataLoader<Int, String?>("myDataLoader")
.load(id)
} |
Beta Was this translation helpful? Give feedback.
-
Bring out your dead! Using the beautiful answer from @dariuszkuc, I implemented this pattern to allow for more easy integration of one field into multiple fields: @Configuration
class DataLoaderConfiguration(private val accountStatusDataLoader: AccountStatusDataLoader) {
@Bean
fun dataLoaderRegistryFactory(): DataLoaderRegistryFactory {
return object : DataLoaderRegistryFactory {
override fun generate(): DataLoaderRegistry {
val registry = DataLoaderRegistry()
registry.register(AccountStatusDataLoader.name, accountStatusDataLoader.getLoader())
return registry
}
}
}
}
@Component
class AccountStatusDataLoader(private val accountStatusDao: AccountStatusDao) {
companion object {
const val name = "AccountStatusDataLoader"
}
fun getLoader(): DataLoader<Long, AccountStatus> =
DataLoader.newMappedDataLoader { ids ->
CompletableFuture.supplyAsync {
ids.associateWith { accountStatusDao.getById(it) }
}
}
}
interface AccountStatusEdge {
val accountStatusId: Long
fun accountStatus(environment: DataFetchingEnvironment): CompletableFuture<AccountStatus?> {
return environment.getDataLoader<Long, AccountStatus?>(AccountStatusDataLoader.name).load(accountStatusId)
}
}
data class Account (
val accountId: Long,
override val accountStatusId: Long,
) : AccountStatusEdge
|
Beta Was this translation helpful? Give feedback.
Disclaimer: I'm not an expert on dataloader as I haven't used it but below should work.
Instead of a
lateinit
property which as you mentioned cannot be null, you should be able to expose nullable GraphQL field through a function that accepts theDataFetchingEnvironment
and use that to access the dataloader, e.g.