Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhancement: async requestInterceptor #6

Open
Discountrobot opened this issue Jan 6, 2016 · 2 comments
Open

enhancement: async requestInterceptor #6

Discountrobot opened this issue Jan 6, 2016 · 2 comments

Comments

@Discountrobot
Copy link
Contributor

The following code snippet will introduce a race condition, should one try to call SomeRESTClient before the _session has been populated, by the createSession request.

@Injectable()
@BaseUrl('https://api.someplace.com')
@DefaultHeaders({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
})
export class SomeRESTClient extends RESTClient {

  private _session: any

  constructor(private _http: Http) {
    super(_http)
    this.setup()
  }

  protected requestInterceptor(req: Request) {
    if (this._session) {
      req.headers.append('Token', this._session.token)
    }
  }

  @POST('/sessions')
  @Produces(MediaType.JSON)
  private createSession( @Body data ): Observable<any> { return null }

  private setup () {
    let api_key = 'xxxx'
    this.createSession({ api_key }).subscribe(session => this._session = session)
  }
}

We should add the possibility to have the requestInterceptor return a promise or similar.

@Discountrobot Discountrobot changed the title enhancement: async requestIntercepter enhancement: async requestInterceptor Jan 6, 2016
@Paldom
Copy link
Owner

Paldom commented Jan 12, 2016

Could you please give a small example (or simply extend the one above), how would you use the promise if requestInterceptor has support for that?

@zhakhalov
Copy link

Hello
+1 to feature

Async interceptor could be important for OAuth process, which can has temporary token, needed to update before sending request

Could you also pass Response to responseInterceptor instead of Observable

Here is small example of async interceptor.

@Injectable()
@BaseUrl('https://api.someplace.com')
@DefaultHeaders({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
})
export class SomeRESTClient extends RESTClient {

  constructor(
    @Inject(Http) http: Http
    @Inject(AuthService) private auth: AuthService
  ) {
    super(http)
    this.setup()
  }

  protected requestInterceptor(req: Request): Promise<void> {
    return this.auth
      .token(token => {
        req.headers.append('Autorization', `Bearer ${token}`)
      })
  }

  protected responseInterceptor(res: Response): Promise<void> {
    // do some stuff with raw response
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants