borchero / Squid

Declarative and Reactive Networking for Swift.

Home Page:https://squid.borchero.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fetch Token Before Sending Request

AAAstorga opened this issue · comments

Hello,

I stumbled upon this library and decided to give it a try! I have a public and private API used by my app and the private API is behind Firebase Authentication. Is there a way to fetch the authorization token right before making the request. The call to get the token is async.

if let cu = firebaseAuth.currentUser {
                    cu.getIDTokenForcingRefresh(true) { (token, error) in
                        if let t = token {
                            urlRequest.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization")
                            closure(.success(urlRequest))
                        } else {
                            closure(.failure(.underlying(NetworkingErrors.noToken, nil)))
                        }
                    }
                }

Here is an example of how I currently do it. This closure is called after the new token as been set. I see there is a synchronous way to accomplish this with this library, but how about an async one? 😄

Great to hear that you decided to give Squid a try! :)

So, on a request level, it is rather easy to do as you can just chain publishers. So you would create a Future<String, Error> publisher which yields the token and then call flatMap, initializing a new request with the token and scheduling it.

However, I see the use case for service-level asynchronous initialization of the header, so I will think of a way to incorporate that in the API.

Asynchronous headers are implemented in version 1.2.0 (see documentation here) ... hope that helps your use case ;)