jeddeloh / rescript-apollo-client

ReScript bindings for the Apollo Client ecosystem
MIT License
127 stars 18 forks source link

Runtime error with ApolloClient.Utilities.getOperationDefinition function #135

Closed LeoLeBras closed 2 years ago

LeoLeBras commented 2 years ago

Hello

Once again many thanks for your great bindings. 👏🥳

I am currently experiencing a bug in the use of the ApolloClient.Utilities.getOperationDefinition function.

let terminatingLink = ApolloClient.Link.split(~test=({query}) =>
  switch ApolloClient.Utilities.getOperationDefinition(query) {
  | Some({kind, operation, name: {value}}) =>
    kind === "OperationDefinition" &&
    operation === "query" &&
    value->Js.String2.startsWith("Analytics")
  | _ => false
  }
, ~whenTrue=httpAnalyticsLink, ~whenFalse=httpGatewayLink)

It creates an error if I have a graphql query that takes this form (no operation name).

query ($id: ID!) {
  user(id: $id) { ... }
}

In this cas, the name property is undefined. So it is not possible to access value property. So I applied this patch ⬇️

diff --git a/node_modules/rescript-apollo-client/src/graphql/language/ApolloClient__Graphql_Language_Ast.res b/node_modules/rescript-apollo-client/src/graphql/language/ApolloClient__Graphql_Language_Ast.res
index 1c007fa..80f26c6 100644
--- a/node_modules/rescript-apollo-client/src/graphql/language/ApolloClient__Graphql_Language_Ast.res
+++ b/node_modules/rescript-apollo-client/src/graphql/language/ApolloClient__Graphql_Language_Ast.res
@@ -172,7 +172,7 @@ module OperationDefinitionNode = {
   type t = {
     kind: string,
     loc: option<Location.t>,
-    name: NameNode.t,
+    name: option<NameNode.t>,
     operation: OperationTypeNode.t,
     variableDefinitions: option<array<VariableDefinitionNode.t>>,
     directives: option<array<DirectiveNode.t>>,

And change that ⬇️

let terminatingLink = ApolloClient.Link.split(~test=({query}) =>
  switch ApolloClient.Utilities.getOperationDefinition(query) {
-  | Some({kind, operation, name: {value}}) =>
+  | Some({kind, operation, name: Some({value})}) =>
    kind === "OperationDefinition" &&
    operation === "query" &&
    value->Js.String2.startsWith("Analytics")
  | _ => false
  }
, ~whenTrue=httpAnalyticsLink, ~whenFalse=httpGatewayLink)

Do you need a pull request?

Greetings from France 🇫🇷

Léo

jeddeloh commented 2 years ago

Thanks! I checked the types and clearly just an oversight on my part. I'm going to make a PR here shortly anyway, so I'll include this.

jeddeloh commented 2 years ago

Resolved in #136

LeoLeBras commented 2 years ago

Thanks !! 🎅:evergreen_tree: