Hi everyone. Does anyone have implemented a dynami...
# exposed
v
Hi everyone. Does anyone have implemented a dynamic field update. I mean, one function that update the given property with given value (maybe with generics) ?
t
What is the use-case?
v
Supose I have a User table:
Copy code
id
name
age
I would like to listen to a PATCH requisition with
val property, val newValue
and perform an update on said property`s table. like
if (property == "name") then [update name]
, but maybe using generics instead
t
You want it on DSL level? Like intercept any updates on some table and override a value?
v
What I need is somthing like this:
Copy code
fun patchUser(property: String, newValue: Any) = transaction { 
    Users.update { 
        it[<property>] = newValue
    }
}
t
It looks like not very type safe approach. Where
property
and
newValue
are come from?
v
You are right, it is not safe at all. It is comming from a http request. Any toughts on a good way to implement PATCH (update only a few values of the entity) requests?
s
You'd typically bind your patch request body to a data class or something. That gives you your type safety.
How you do that binding depends on the web framework you are using.
v
Thats what I thought, Maybe the best aproach is to create a model with nullable properties only to wrap patch requests, and in the transaction i check if not null, update:
Copy code
fun patchUser(patchUser: PatchUser) = transaction { 
    Users.update { 
        if(patchUser.name) != null
            it[name] = patchUser.name
        if(etc...)
    }
}
Please share if there is a cleaner way to do it
t
You could use reflection but it will slower your app and will make your code less readable.
✔️ 1