grpc-ecosystem / protoc-gen-grpc-gateway-ts

protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript clients that connect the web frontend and golang backend fronted by grpc-gateway.
Apache License 2.0
142 stars 51 forks source link

Is there anyway to pass custom headers ? #13

Closed didierfranc closed 3 years ago

didierfranc commented 3 years ago

It is useful to pass a header like Authorization to the query, I can't find a way to pass it

abatilo commented 3 years ago

@didierfranc did you find your answer?

atreya2011 commented 3 years ago

@abatilo Given a service definition like this:

  static HTTPPostWithStarBodyPath(req: HttpPostRequest, initReq?: fm.InitReq): Promise<HttpPostResponse> {
    return fm.fetchReq<HttpPostRequest, HttpPostResponse>(`/post/${req["a"]}/${req["c"]}`, {...initReq, method: "POST", body: JSON.stringify(req)})
  }

Just pass the headers as fetch options like this as the second parameter (initReq)

{
    pathPrefix: `endpointURL`,
    headers: {
      Authorization: `Bearer token`,
    },
}
abatilo commented 3 years ago

Ah, that makes sense. It almost looks like initReq are just regular params for a fetch request!

Thank you very much.

atreya2011 commented 3 years ago

@abatilo Yes you are correct, initReq just extends the regular params object for a fetch request and adds pathPrefix for appending the endpoint URL prefix 👍🏼 So you can add all the params that are applicable for the Fetch API.

didierfranc commented 3 years ago

What's your thought about setting those params one time (in a constructor) instead of passing them to every method call?

atreya2011 commented 3 years ago

Yes, I did give that idea some consideration. Let's take React as an example and assume that you have two components: one calling a ListUsers RPC and another calling an AddUser RPC. In each of those components, you have to instantiate the UserService class and pass the params to a constructor. So you are technically passing the params twice (once in each component). And this is the same as passing the params to every method call.

abatilo commented 3 years ago

Yes, I did gave that idea some consideration. Let's take React as an example and assume that you have two components: one calling a ListUsers RPC and another calling an AddUser RPC. In each of those components, you have to instantiate the UserService class and pass the params to a constructor. So you are technically passing the params twice (once in each component). And this is the same as passing the params to every method call.

There are ways around that though. If you create a ContextProvider for the client, then you can have multiple components use the same instance.

atreya2011 commented 3 years ago

@abatilo I see what you mean. Perhaps you can raise this as a separate issue and check the feasibility of making a PR where you can pass the params to a constructor.