qs icon indicating copy to clipboard operation
qs copied to clipboard

Support nested structs

Open dcu opened this issue 4 years ago • 2 comments

The following struct is not supported:

type Inner struct {
	A string
	B string
}

type Query struct {
	Search     string
	Page       int
	PageSize   int
	Categories []Inner `qs:"category"`
}

dcu avatar Mar 16 '20 13:03 dcu

Query strings naturally support only key-value pairs where the value can be an array if a given key is used multiple times in the query string. Supporting nested data structures could be implemented relatively easily but there is no standard way of doing it and it usually results in ugly URLs.

When I implemented the library I explored the options and decided not to add this feature to discourage people from encoding overly complicated data structures into unreadable URLs. I consider that to be an anti-pattern and an abuse of URL query strings.

I understand that a lot of people want to use the same data structures for many things in the codebase but that is often a bad design choice. In my experience it's often better to use separate structs for in-memory representation and different types of serialisation (database, url query string, etc...) even if it results in some boring/bloated but utterly simple code that copies data between structs that might have the exact same (at least in the initial implementation) or very similar shapes.

A pattern (or anti-pattern) that I see quite often is using the same struct for DB access and JSON-API. Some people think it'd look silly to duplicate the same struct and tag them up separately for json api and db. Sharing the same struct results in a very simple first implementation without boring/simple code copying between the strucst but a single struct ties the API and DB schema together despite the fact that these things usually diverge over time and have to be changed separately at different points in time. How is this related to URL query strings? I think it's better to dedicate a separate struct to query string serialisation and copy between that struct and other in-memory representations of the data if they are so different. This has the advantage of decoupling the URL format (that is better kept backwards compatible over time) from in-memory formats that might have to change more often during refactors. You might also want to keep around more than one URL serialiser structs if you change the format but want to support the old URL format at least for a period of time. If we have a dedicated struct for query string serialisation then why not support only those features that are naturally supported by query strings (key-value pairs where value is scalar or array)?

pasztorpisti avatar Mar 25 '20 06:03 pasztorpisti

Szia Cser Hunor vagyok, szeretnék kérni egy email címet ha lehet. Köszönöm

cserhunor avatar Nov 01 '23 16:11 cserhunor