Yokan / rebuild
Course 1 8624561

09-networking.md

.codex/skills/compose-kotlin-agent-skills/references/09-networking.md

documentation / design asset322 lines
1# Networking — Ktor, Auth Flows, DTO Mappers, Offline-First23## Contents45- Ktor client setup6- Auth flows — JWT, token refresh, interceptors7- DTO → domain mapper pattern8- Offline-first — local cache + remote sync9- Error handling — network → domain errors1011## Ktor Client Setup1213```kotlin14fun createHttpClient(tokenProvider: TokenProvider): HttpClient {15    return HttpClient {16        // JSON serialization17        install(ContentNegotiation) {18            json(Json {19                ignoreUnknownKeys = true    // API adds fields, don't crash20                isLenient = true            // tolerate minor JSON issues21                encodeDefaults = false      // skip null/default in requests22            })23        }2425        // Logging (debug only)26        install(Logging) {27            level = LogLevel.HEADERS  // BODY for full debug, HEADERS for prod28        }2930        // Timeout31        install(HttpTimeout) {32            requestTimeoutMillis = 30_00033            connectTimeoutMillis = 10_00034        }3536        // Default request config37        defaultRequest {38            url("https://api.example.com/v1/")39            contentType(ContentType.Application.Json)40        }41    }42}43```4445```toml46[dependencies]47ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }48ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }49ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }50ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }51ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }52ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "ktor" }53```5455## Auth — JWT Token Refresh5657```kotlin58class AuthInterceptor(59    private val tokenStore: TokenStore,60    private val authApi: AuthApi61) {62    fun install(config: HttpClientConfig<*>) {63        config.install(HttpSend) {64            intercept { request ->65                // Attach token66                val token = tokenStore.getAccessToken()67                if (token != null) {68                    request.headers.append("Authorization", "Bearer $token")69                }7071                val response = execute(request)7273                // If 401, refresh token and retry once74                if (response.response.status == HttpStatusCode.Unauthorized) {75                    val refreshed = refreshToken()76                    if (refreshed) {77                        request.headers.remove("Authorization")78                        request.headers.append(79                            "Authorization",80                            "Bearer ${tokenStore.getAccessToken()}"81                        )82                        execute(request)83                    } else {84                        response  // refresh failed, return 40185                    }86                } else {87                    response88                }89            }90        }91    }9293    private suspend fun refreshToken(): Boolean {94        return try {95            val refreshToken = tokenStore.getRefreshToken() ?: return false96            val response = authApi.refreshToken(refreshToken)97            tokenStore.saveTokens(response.accessToken, response.refreshToken)98            true99        } catch (e: Exception) {100            tokenStore.clearTokens()101            false102        }103    }104}105```106107### Token Storage108109```kotlin110class TokenStore(private val dataStore: DataStore<Preferences>) {111    private val ACCESS_TOKEN = stringPreferencesKey("access_token")112    private val REFRESH_TOKEN = stringPreferencesKey("refresh_token")113114    suspend fun getAccessToken(): String? =115        dataStore.data.first()[ACCESS_TOKEN]116117    suspend fun saveTokens(access: String, refresh: String) {118        dataStore.edit { prefs ->119            prefs[ACCESS_TOKEN] = access120            prefs[REFRESH_TOKEN] = refresh121        }122    }123124    suspend fun clearTokens() {125        dataStore.edit { it.clear() }126    }127}128```129130## DTO → Domain Mapper Pattern131132```kotlin133// Network DTO — matches API JSON shape134@Serializable135data class AccountDto(136    val id: String,137    @SerialName("service_name") val serviceName: String,138    @SerialName("account_name") val accountName: String,139    @SerialName("secret_key") val secretKey: String,140    @SerialName("icon_url") val iconUrl: String?,141    @SerialName("created_at") val createdAt: String  // ISO 8601142)143144// Domain model — what the app actually uses145data class AuthAccount(146    val id: String,147    val serviceName: String,148    val accountName: String,149    val secretKey: String,150    val iconUrl: String?,151    val createdAt: LocalDateTime152)153154// Mapper155fun AccountDto.toDomain() = AuthAccount(156    id = id,157    serviceName = serviceName,158    accountName = accountName,159    secretKey = secretKey,160    iconUrl = iconUrl,161    createdAt = LocalDateTime.parse(createdAt)162)163164fun AuthAccount.toDto() = AccountDto(165    id = id,166    serviceName = serviceName,167    accountName = accountName,168    secretKey = secretKey,169    iconUrl = iconUrl,170    createdAt = createdAt.toString()171)172```173174**Why separate DTO from domain:**1751. API shape changes don't cascade through your app1762. `@SerialName` annotations don't pollute domain1773. Date parsing happens once in mapper, not throughout codebase1784. Null handling and defaults isolated in mapper179180## API Service Layer181182```kotlin183class AuthApiService(private val client: HttpClient) {184185    suspend fun getAccounts(): List<AccountDto> {186        return client.get("accounts").body()187    }188189    suspend fun getAccountById(id: String): AccountDto {190        return client.get("accounts/$id").body()191    }192193    suspend fun createAccount(request: CreateAccountRequest): AccountDto {194        return client.post("accounts") {195            setBody(request)196        }.body()197    }198199    suspend fun deleteAccount(id: String) {200        client.delete("accounts/$id")201    }202203    suspend fun refreshToken(refreshToken: String): TokenResponse {204        return client.post("auth/refresh") {205            setBody(RefreshRequest(refreshToken))206        }.body()207    }208}209```210211## Offline-First Pattern212213```kotlin214class AuthRepositoryImpl(215    private val dao: AuthAccountDao,216    private val api: AuthApiService217) : AuthRepository {218219    // UI always reads from local DB220    override fun getAllAccounts(): Flow<List<AuthAccount>> =221        dao.getAllAccounts().map { entities -> entities.map { it.toDomain() } }222223    // Sync: remote → local, UI auto-updates via Flow224    override suspend fun sync(): Result<Unit> {225        return safeApiCall {226            val remoteDtos = api.getAccounts()227            val entities = remoteDtos.map { it.toDomain().toEntity() }228            dao.replaceAllAccounts(entities)229        }230    }231232    // Write: local first, then remote233    override suspend fun addAccount(account: AuthAccount): Result<Unit> {234        // Always write locally first — instant UI update235        dao.insertAccount(account.toEntity())236237        // Then sync to remote238        return safeApiCall {239            api.createAccount(account.toCreateRequest())240        }241    }242}243```244245### Sync Strategy246247```kotlin248class SyncManager(249    private val repository: AuthRepository,250    private val connectivityMonitor: ConnectivityMonitor251) {252    // Sync on app start253    suspend fun syncOnStart() {254        if (connectivityMonitor.isOnline()) {255            repository.sync()256        }257    }258259    // Observe connectivity and sync when back online260    fun observeConnectivity(): Flow<Boolean> =261        connectivityMonitor.isOnlineFlow262            .distinctUntilChanged()263            .filter { it }  // only when transitioning to online264            .onEach { repository.sync() }265}266```267268## Error Handling — Network to Domain269270```kotlin271sealed interface NetworkError {272    data class Http(val code: Int, val message: String) : NetworkError273    data object NoConnection : NetworkError274    data object Timeout : NetworkError275    data class Unknown(val cause: Throwable) : NetworkError276}277278suspend fun <T> safeApiCall(block: suspend () -> T): Result<T> {279    return try {280        Result.success(block())281    } catch (e: CancellationException) {282        throw e  // never swallow cancellation283    } catch (e: ClientRequestException) {  // 4xx284        Result.failure(NetworkError.Http(e.response.status.value, e.message))285    } catch (e: ServerResponseException) {  // 5xx286        Result.failure(NetworkError.Http(e.response.status.value, e.message))287    } catch (e: HttpRequestTimeoutException) {288        Result.failure(NetworkError.Timeout)289    } catch (e: IOException) {290        Result.failure(NetworkError.NoConnection)291    } catch (e: Throwable) {292        Result.failure(NetworkError.Unknown(e))293    }294}295```296297### Map to UI-Friendly Message298299```kotlin300fun NetworkError.toUserMessage(): String = when (this) {301    is NetworkError.Http -> when (code) {302        401 -> "Session expired. Please sign in again."303        403 -> "You don't have permission for this action."304        404 -> "Not found."305        429 -> "Too many requests. Please wait a moment."306        in 500..599 -> "Server error. Please try again later."307        else -> "Something went wrong (Error $code)."308    }309    NetworkError.NoConnection -> "No internet connection."310    NetworkError.Timeout -> "Request timed out. Check your connection."311    is NetworkError.Unknown -> "Unexpected error occurred."312}313```314315## Anti-Patterns316317- **Catching `Exception` instead of specific types** → catches `CancellationException`, breaks coroutines318- **Parsing JSON in composable** → CPU-heavy. Parse in repository/ViewModel on background dispatcher319- **Hardcoded base URL** → use BuildConfig or dependency injection for different environments320- **No timeout** → default Ktor has no timeout. Set explicit `HttpTimeout`321- **Logging `LogLevel.BODY` in production** → leaks sensitive data to logcat. Use `HEADERS` or `INFO`322- **Token in URL query param** → visible in logs, server access logs, browser history. Always use Authorization header323

Search chapters, reference and source filenames.