I am new to Purescript and I am trying to write a function that can take any record value and iterate over the fields and values and build a querystring.
I am thinking something like:
buildQueryString :: forall a. PropertyTraversible r => r -> String
which I want to use like this:
buildQueryString {name: "joe", age: 10} -- returns: "name=joe&age=10"
Is there a way to write something like that in Purescript with existing idioms or do I have to create my own custom Type Class for this?
This is possible with purescript-generics but it only works on nominal types, not on any record. But it saves you boilerplate, since you can just derive the instance for
Generic
, so it would work with any data or newtype without further modification.Downside is, you have to make some assumptions about the type: like it only contains one record and the record does not contain arrays or other records.
Here is a hacky demonstration how it would work:
purescript-generics-rep is newer, so possibly there is a better solution, maybe even on any record. I have not tried that (yet).
I'm sure that it can be shorter, but here is my implementation based on
purescript-generic-rep
(inspired bygenericShow
). This solution uses typeclasses - it seems to be standard approach withgeneric-rep
:buildQueryString
expects value of type with single constructor which contains a record (possibly justnewtype
) because it is impossible to derive aGeneric
instance for "unwrapped"Record
type.If you want to handle also
Array
values etc. thenencodeValue
should probably return values of typeArray String
.