Advertisement
Guest User

Untitled

a guest
May 25th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. module type Config = {
  2. type t;
  3.  
  4. let query: string;
  5. let parse: Js.Json.t => t;
  6. };
  7.  
  8. module Provider = {
  9. [@bs.module "@apollo/react-hooks"] [@react.component]
  10. external make:
  11. (~client: ApolloClient.generatedApolloClient, ~children: React.element) =>
  12. React.element =
  13. "ApolloProvider";
  14. };
  15.  
  16. module Query = {
  17. module Make = (Config: Config) => {
  18. [@bs.module] external gql: ReasonApolloTypes.gql = "graphql-tag";
  19.  
  20. type error = {. "message": string};
  21.  
  22. [@bs.deriving abstract]
  23. type options = {
  24. [@bs.optional]
  25. variables: Js.Json.t,
  26. };
  27.  
  28. [@bs.module "@apollo/react-hooks"]
  29. external _useQuery:
  30. (ReasonApolloTypes.queryString, Js.Nullable.t(options)) =>
  31. {
  32. .
  33. "data": Js.Nullable.t(Js.Json.t),
  34. "loading": bool,
  35. "error": Js.Nullable.t(error),
  36. } =
  37. "useQuery";
  38.  
  39. type resultVariant =
  40. | Data(Config.t)
  41. | Error(error)
  42. | Loading
  43. | NoData;
  44.  
  45. type result = {
  46. data: option(Config.t),
  47. error: option(error),
  48. loading: bool,
  49. };
  50.  
  51. let use = (~options=?, ()) => {
  52. let jsResult =
  53. _useQuery(gql(. Config.query), Js.Nullable.fromOption(options));
  54.  
  55. let result = {
  56. data:
  57. jsResult##data->Js.Nullable.toOption->Belt.Option.map(Config.parse),
  58. loading: jsResult##loading,
  59. error: jsResult##error->Js.Nullable.toOption,
  60. };
  61.  
  62. switch (result) {
  63. | {data: Some(data)} => Data(data)
  64. | {error: Some(error)} => Error(error)
  65. | {loading: true} => Loading
  66. | _ => NoData
  67. };
  68. };
  69. };
  70. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement