planety / prologue

Powerful and flexible web framework written in Nim
https://planety.github.io/prologue
Apache License 2.0
1.23k stars 47 forks source link

RFC - Add generic proc to parse `FormPart` into a nim object type #200

Open PhilippMDoerner opened 1 year ago

PhilippMDoerner commented 1 year ago

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

1) The object-type to convert the form data to, which gives you the names and types of the individual fields you'd expect 2) The form-data itself

So I propose 2 procs:

1) parseForm for handling the parsing in general, and 2) 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:

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.

PhilippMDoerner commented 1 year ago

An alternative suggestion coming from hotdog was to keep this RFC as a separate package that could be used framework independently to parse one object into another.

It would still have a parseForm proc, but it would implicitly call another fromSource proc, which said package could define for the major frameworks (prologue, jester and maybe nexus once it is released, or entirely unrelated frameworks). I'm not entirely convinced of the value of such an approach as I'm pretty sure that in general other frameworks might have their own solution better tailored to their needs, but it is an option.