What is the recommended ktor way of returning diff...
# ktor
f
What is the recommended ktor way of returning different set of data depending on who is logged in? E.g. when requesting a user object if I am the owner of it to return everything and when I am not the owner to just return some information. In the past I would have used JSON Views (I use Jackson) but I don't think there is currently a way to use JSON Views with ktor
t
How are you handling identity? Oauth2?
f
For example. I am ok with programatic telling what type of user it is.
For SpringBoot I for example return a
MappingJacksonValue
instance as my return entity. Which takes in the entity object and a view class to use. And the serialized that entity with respecting the view class to json
t
You can use jackson with ktor (I have not) and creat json objects from data classes to respond with. You would just need to construct the data class to respond with and handle your identity logic. We use gson. Ktor has good docs https://ktor.io/servers/features/content-negotiation/gson.html
I am on mobile now so sorry for formatting
I am not 100% sure what you are asking but hopefully that helps point you in right direction.
f
Yeah I know but my question is not if I can create json from a data class but rather how I can limit what data is returned in the json based on some programmatic determination (e.g. the logged in user)
t
How are you determining who the user is?
When you build the response only include the relevant data base on the user
However you are handling identity.
f
Ok let me show you an example of what I do in Spring Boot:
Copy code
class User {
@JsonView(Public.class)
private String id;

@JsonView(Public.class)
private String name;

@JsonView(Private.class)
private String email;
}

@Get("/profile/{id}")
public MappingJacksonValue getProfile(String id, Principal p) {
  User user = loadUserById(id);
  return new MappingJacksonValue(user, user.id.equals(p.getId()) ? Private.class : Public.class);
}
This way I just map all fields into my data object (or use a data object from the database) and on Controller level let Jackson know what data should be included/excluded
a
@fkrauthan You could use Jackson’s @JsonView annotation. https://www.baeldung.com/jackson-json-view-annotation
f
Yeah but ktor has no native support for it (I have no way to specify what view to use). But I actual found a solution. I created a StdSerializer that can serialize a special entity that contains the value and the json view to use. It seem to work 🙂