https://kotlinlang.org logo
#exposed
Title
# exposed
v

Vinicius Araujo

09/24/2019, 11:55 PM
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

tapac

09/25/2019, 5:45 AM
What is the use-case?
v

Vinicius Araujo

09/25/2019, 11:59 AM
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

tapac

09/25/2019, 1:49 PM
You want it on DSL level? Like intercept any updates on some table and override a value?
v

Vinicius Araujo

09/25/2019, 3:02 PM
What I need is somthing like this:
Copy code
fun patchUser(property: String, newValue: Any) = transaction { 
    Users.update { 
        it[<property>] = newValue
    }
}
t

tapac

09/25/2019, 3:14 PM
It looks like not very type safe approach. Where
property
and
newValue
are come from?
v

Vinicius Araujo

09/25/2019, 5:07 PM
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

Shawn A

09/25/2019, 5:19 PM
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

Vinicius Araujo

09/25/2019, 5:57 PM
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

tapac

09/27/2019, 9:38 AM
You could use reflection but it will slower your app and will make your code less readable.
✔️ 1
4 Views