teamwalnut / graphql-ppx

GraphQL language primitives for ReScript/ReasonML written in ReasonML
https://graphql-ppx.com
MIT License
256 stars 53 forks source link

Add functions for parsing/serializing the 't_variables' type #220

Open austindd opened 3 years ago

austindd commented 3 years ago

Right now I have some compelling use cases for generating a record to represent the t_variables type along with functions to parse and serialize that type. The biggest thing for me is writing a server endpoint which decodes the input for a mutation. Right now I have to manually define functions to transform data like Js.Json.t -> Raw.t_variables -> t_variables.

I see that the Operation module type provides the following:

let serializeVariables: t_variables => Raw.t_variables

There is also the makeVariables function, but that doesn't help much because I really need to convert from Js.Json.t, which leaves me writing decoders for that. Ideally we would generate code for the entire round trip between Js.Json.t and t_variables. This has been done for the response type t, so it makes sense to fill in the gap for t_variables.

jfrolich commented 3 years ago

Ah so a parseVariables function? The conversion of Js.Json.t -> Raw.t_variables is zero cost if you are sure the JSON provided are valid arguments to the query. Usually once you have Raw.t_variables you can pass it in a query if the library allows you to pass in raw variables. Can you explain more of the use case? If you are not sure if the arguments are valid, you probably also want a function that validates the JSON and remove all redundant keys and then produce a Raw.t_variables (this is outside of the scope of graphql-ppx I think, and why not go directly to t_variables if you are taking this route?). A parseVariables might make sense but I don't see a compelling use-case for it yet.

austindd commented 3 years ago

Yeah, I can see why it might not be obvious. Here’s a better description of the use case.

I have dozens of serverless functions written in Reason. The request handler takes a request with a JSON body, which should (in most cases) match the shape of the query/mutation variables sent from the client. In each case, I have to manually parse the JSON body, but it would be nice to have these functions generated by the ppx. I am currently using the module type to infer the appropriate input/response types in my handler function, and using the generated serializer to produce a JSON string for the response. I would like to do the same kind of thing with the input data as well.

I suppose it would be ideal to have the parser function return an option/result type, but I could live with exception-raising as well.

I can post a minimum-viable code snippet later when I’m at my PC of you want.