Skip to content

Instantly share code, notes, and snippets.

@thrawn01
Created July 20, 2023 14:57
Show Gist options
  • Save thrawn01/452588d92d3b814f941f626ca93a4150 to your computer and use it in GitHub Desktop.
Save thrawn01/452588d92d3b814f941f626ca93a4150 to your computer and use it in GitHub Desktop.

Sorting

Everyone does it differently 😭 and most query string parsers don't support LHS or RHS parsing or building. Prefer RHS for clarity and simplicity of parsing. I don't like the - or + operators because It's easy to over look.

Options from different sources

  • ChatGPT /users?sort=email,asc
  • RHS Single Field /users?sort=email:ASC
  • RHS Multiple Fields /users?sort=email:asc,name:desc
  • RHS Multiple Fields Keyed /users?sort=email:asc&sort=name:desc
  • LHS /users?sort=[asc]email
  • LHS Multiple Fields /users?sort=[asc]email,[desc]name
  • RHS Multiple Fields Keyed /users?sort=[asc]email&sort=[desc]name
  • Plus / Minus Operator /users?sort=+email
  • Mailjet /users?sort=email+DESC

Conclusion

Use /users?sort=email:ASC . The direction should be optional and should be case in-sensitive with multiple fields separated by comma (,)

For example /users?sort=email:ASC,name:DESC such that email is sorted first and name is sorted second. Using sort=email:ASC,sort=name:DESC is a risk as some query parameter parsers might return values as a map which could lose the sort order of email then name.

Clients

Not sure I like passing in sort in this way, but it's simple. Users of this client will STILL have to lookup "How to do sorting" in the documentation as either way we do it..... it won't be obvious to the user without looking at the documentation.

// Complex... not really useful?
it := client.ListUsers(ListOptions{ Sort: 
   []Sort{ 
	   {Field: "email", Dir: "asc"}, 
	   {Field: "name", Dir: "desc"}, 
   }
)

// Simple... but string manipulation might be needed in some cases.
it := client.ListUsers(ListOptions{ Sort: "email:asc,name:desc"})

var page []Users
for it.Next(ctx, &page) {
	for _, u := range page {
		fmt.Printf("User: %s Email: %s\n", u.Name, u.Email)
	}
}
@TheNando
Copy link

TheNando commented Jul 20, 2023

As a frontend dev, I'm mostly concerned with the API call. I'd vote for /users?sort=email:asc,name:desc. It may go without saying, but is important to note that when sorting on multiple fields, order does matter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment