prologue
prologue copied to clipboard
RFC - Add generic proc to parse `FormPart` into a nim object type
nonce from the discord server brought up an interesting problem that I think could be solved within the prologue framework: Often times you have HTTP requests with multipart-formdata.
Currently prologue has a Request.FormData
type, that contains the form-data that needs to be parsed. The parsing could be automated, as all you need to know is
- The object-type to convert the form data to, which gives you the names and types of the individual fields you'd expect
- The form-data itself
So I propose 2 procs:
-
parseForm
for handling the parsing in general, and -
toObjectValue
for handling the conversion of a single form-field value in string form to the required object-field type.
The signatures would be as follows:
proc parseForm*[T: object | ref object](form: FormPart, objectType: typedesc[T], skipFieldNames: static seq[string] = @[]): T =
func toObjectValue*(formValue: string, O: typedesc[Option[<UserDefinedType>]]): O =
Prologue would provide the parseForm
proc that takes care of the general logic of transforming FormPart
into an object of type T
.
That parseForm
proc would iterate over the given object type and for each field do the following:
- Try to extract the form-field value from
FormPart
via the object-field name (We could also provide a pragma that allows you to deal with cases where the objcet-field-name and the form-field-name do not match) - Parse the form-field-value into the type of the object-field using the
toObjectValue
proc for the given field-type - Assign the parsed form-field-value to the object-field
Prologue would also provide a basic set of toObjectValue
procs that deal with converting string to fields of type SomeInteger
, SomeFloat
, string
(basically does nothing), bool
and their optional versions.
Users can extend the parsing functionality by defining their own toObjectValue
procs that would need to be available at the place where parseForm
is called.
Finally, it would be possible to "skip" specific fields if there are specific circumstances where they can not be available (yet). One example would be during POST requests where any kind of id
field can not have a value yet, and thus should be allowed to be missing from FormData
.
Would such a feature still be within the scope of prologue? If so, I'd be willing to implement it, as I have already implemented a very similar version in Snorlogue, though with the names toModelValue
and parseFormData
.