package com.zaojiao.app.core.http.common

import com.squareup.moshi.Json
import com.zaojiao.app.core.common.state.DataState

data class NetResult<out T>(
    val status: Int,
    val data: T?,
    @Json(name = "msg")
    val message: String?,
)

fun NetResult<*>.isSuccess(): Boolean {
    return status == 200
}

suspend fun <T> tryRequest(action: suspend () -> DataState<T>): DataState<T> {
    return try {
        action.invoke()
    } catch (e: Throwable) {
        DataState.Failure(e)
    }
}

fun <T> NetResult<T>.toDataState(): DataState<T> {
    return if (this.isSuccess()) {
        DataState.Success(this.data)
    } else {
        DataState.Failure(RuntimeException(this.message))
    }
}