I m using Django Rest Framework and React, but this is more of a conceptual question.
I ve noticed that when querying data from an API, especially on a React-esque frontend, I always run into the same issues.
- API responses are not intrinsically typed
- I cannot specific exactly what fields I d like to get back from the API
- I can t specify dynamic type-safe filtering and sorting.
In an ideal world, I d like to be able to do something like this:
// Using a user model as an example.
export function UserComponent(props: ...){
// `data` is inferred to be of type Pick<User, "email", "lastActive">
const data = myCustomAPIFetch<User>({
model: User
fields: [User.email, User.lastActive],
filters: {
[User.firstName]: "Linus"
} // Similar syntax for sorting
})
return (...)
}
This solves all three issues - it returns the proper type object, filtering/sorting is type-safe, and the exact fields that I want back can be specified.
The solutions that I ve researched here solve some of the problems, but not all.
Graphql - solves #2 and can solve #1, but from what I understand I have to make a new query/resolver for each filter or sort I want to do. Not ideal.
Protobuf - types are cross-language (huge plus), but can only specify a static schema. Can t ask for only the user s email back without making a new message type.
tRPC - only for TS stacks, also doesn t solve #2 or #3.