apollographql / apollo

:rocket: Open source tools for GraphQL. Central repo for discussion.
https://www.apollographql.com
MIT License
2.61k stars 425 forks source link

Possible to customize the url and operation name via a parameter to useQuery and useMutation? #764

Open breathe opened 4 years ago

breathe commented 4 years ago

I wrap calls to useQuery and useMutation in custom hook's like useLocation useSchedule, and so on for the domain objects in my frontend.

I do this for a few reasons:

  1. to keep some of the noise associated with getting the correct type information from these things out of the UI components
  2. so I can reuse these methods in different parts of my application.
  3. its sometimes conveneint to hide some of the details for talking to the backend from frontend developer's who might be newish to react and graphql -- some components really don't need to care about these details.

I'd love to be able to parameterize the operationName -- and to customize the url that will be used to talk to my backend based on the operation name.

My notion is to setup my backend to respond to arbitrary url's -- /api/graphql* -- and then when running in development to generate distinct url's for graphql requests based on the operationName /api/graphql/query/OperationName and /api/graphql/mutation/OperationName or something similar.

Or perhaps I would keep the operationName as is and a new callSite parameter and generate urls like /api/graphql/query/OperationName/callsite ...

I would then enforce that every call site for one of these useFoo methods has to specify this operationName or callsite parameter. This would allow a new developer coming on the project to quickly discover the actual callsite associated with any given http request when browsing the network panel in browser developer tools -- as well as providing much more useful 'at a glance' information by looking at the network panel (the kind of information that used to be inferrable from the URL with REST that is no longer present when every request looks like /api/graphql)

I think this would help people onboard developers to the project quite a bit.

twavv commented 4 years ago

You can kind of do this already:

const link = new HttpLink({
  uri: (operation) => `${GRAPHQL_URL}?operation_name=${encodeURIComponent(operation.operationName)}`
});
const client = new ApolloClient({ ..., link });

You could maybe customize per-query by adding a special variable (haven't tried this though):

const link = new HttpLink({
  uri: (op) => GRAPHQL_URL + (op.variables["__uriExtra"] || ""),
});

// elsewhere
useQuery({
  ...,
  variables: {
    ...,
    __uriExtra: "/foo/bar",
  }),
})