Models
sinew-models / sinew_models: the shapes every Sinew app shares.
What it holds
Domain,RemoteandEntity, kept apart so a backend that renames a field touches one file.- Envelope bases (
ObjectEnvelope,ListEnvelope,PagedEnvelope,VoidEnvelope) that map any backend's body to one domain shape, and report a failure inside a 2xx body. Result: aSuccesswith the backend's message, or a typedFailure.ViewState:Loading,DoneandFailed, whereLoadingandFailedcan keep the previous data.PagingDomainandPagingMetaDomain: one page shape for every backend.
Map a body to the domain
- Kotlin
- Dart
// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Models.kt#models
/** What the app needs, in business language. */
data class Order(val id: Int, val title: String) : Domain
/** What the backend sends, shaped like its JSON. */
@Serializable
class OrderRemote(val id: Int, val title: String) : Remote<Order>() {
override fun toDomain() = Order(id, title)
}
/** A response body: one order under `data`. */
@Serializable
class OrderEnvelope(override val data: OrderRemote? = null) : ObjectEnvelope<OrderRemote, Order>()
Sinew assumes no JSON keys: your envelope subclass declares its backend's fields. An object envelope's toDomain fails with a parse error when its data is absent; a list envelope maps an absent list to an empty one.
Read a Result
- Kotlin
- Dart
// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Models.kt#result
fun describe(result: Result<Order>): String = result.fold(
onSuccess = { order -> "Loaded ${order.title}" },
onFailure = { error -> "Failed: ${error.code}" },
)
Good to know
ViewStatekeeps no success message: a one-time reaction is an effect, never state.- A
Failedstate keeps the exception, never pre-rendered text, so a language switch re-renders it. - On Kotlin, a generic envelope (
PagedResponse<OrderRemote, Order>) needs a serializer for its domain type argument, though the domain is never parsed: declare one withDomainNotParsed.