I'm building a GraphQL API. I'm want to allow users to specify how records should be sorted, using multiple sorts.
What should be possible
If I expose the ability to sort monsters by name, birthdate, and id, users should be able to get the API to sort by any combination of those, including (in SQL terms):
ORDER BY name ASCORDER BY name ASC, birthdate DESC, id ASC- ... etc
What won't work
A single map, like this:
sorts: [{name: DESC, id: ASC}]
...would not tell me the order in which the sorts should be applied (maps are unordered).
What works OK, but isn't ideal
Currently, I accept a list of maps, like this:
sorts: [{name: DESC}, {id: ASC}]
Each map represents an input object, which has fields like name and id, which are enums with possible values ASC and DESC. I expect only one field to be filled per input object. ~But I don't know a way to enforce that.~
This is awkward because:
- It would be easy for users to typo their sort parameters as a single map
- I can't specify a default (like
ASCforid) without having it added to every input object map
Is there a more idiomatic way of accepting an ordered list of sort parameters?
Update
I've now added a user-facing explanatory error when there is more than one key per map. With this change, I think this strategy is OK, but I'm still happy to hear of better ways in the future if they arise.