DEV Community

Discussion on: ReasonML for production React Apps? ๐Ÿค” (Part 2)

Collapse
 
seif_ghezala profile image
Seif Ghezala ๐Ÿ‡ฉ๐Ÿ‡ฟ

As in a simpler example or a simpler way of achieving the same thing? If it's the latter, and you know how to do it, I'd love to receive some guidance and I refactor the article's example.

Collapse
 
yawaramin profile image
Yawar Amin • Edited

Check out github.com/ryb73/ppx_decco , it's a JSON codec PPX. It should work something like this:

[@decco] type error = {message: string};
[@decco] type response = {
  // other response fields,
  error: option(error),
};

Now it can decode a Js.Json.t that you got from Fetch.Response.json:

|> then_(response =>
  switch (response_decode(response)) {
  | Belt.Result.Ok({error: Some({message})}) =>
    reject(PostError(message))
  | response =>
    resolve(response))

This will resolve with a Js.Promise.t(Belt.Result.t(response, error)) meaning the service didn't return an error message but the JSON may or may not have parsed successfully, or reject with your exception containing the service error message.

Thread Thread
 
seif_ghezala profile image
Seif Ghezala ๐Ÿ‡ฉ๐Ÿ‡ฟ • Edited

This syntax looks much cleaner ๐Ÿคฉ. I will give it a try soon with the Request module and comment about it in this part of the article. Thank you!