I have two reactive methods in "Layer A" that's exposed to the app:
LAYER A - publicly accessible methods to the rest of the app
public Single<ResponseData> postMyData(ReqData data, Long id) {
if (!isUserLoggedIn()) return postLogin().andThen(postData(data, id));
return postData(data, id);
}
public Completable postLogin() {
Account account = getAccountData();
ReqLoginData loginData = new ReqLoginData(account.email, account.pass, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET);
Single<ResponseLogin> singlePostLogin = postLogin(loginData);
return Completable.create(subscriber -> singlePostLogin.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(loginResponse -> {
// Success
storeAccessToken(loginResponse);// *** this will recreate apiClient with new access token
if (!subscriber.isDisposed()) subscriber.onComplete();
}, throwable -> { if (!subscriber.isDisposed()) subscriber.onError(throwable);}
));
}
LAYER B - only accessible by Layer A
public Single<ResponseLogin> postLogin(ReqLoginData loginData) {
Log.d(TAG, "using apiClient "+apiClient.toString());
Single<Response<ResponseLogin>> postLogin = apiClient.postLogin(loginData);
return Single.create(subscriber -> postLogin.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
}));
}
public Single<ResponseData> postData(ReqData data, Long id) {
Log.d(TAG, "using apiClient "+apiClient.toString());
Single<Response<ResponseData>> postData = apiClient.postData(id, data);
return Single.create(subscriber -> postData.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
}));
}
LAYER C - API Interface
#Headers({"Content-Type: application/json"})
#POST(Constants.API_PREFIX + "/auth/token/")
Single<Response<ResponseLogin>> postLogin(#Body ReqLoginData reqLoginData);
#Headers({"Content-Type: application/json"})
#POST(Constants.API_PREFIX + "/data/{id}/")
Single<Response<ResponseData>> postData(#Path("id") Long id, #Body ReqData reqData);
A huge challenge for me at the moment is to make sure the user is logged-in before attempting to POST data. So, using postLogin().andThen(postData(data, id)) made sense to me :
At the time of my late-night development, it seemed that both methods postLogin() and postData() are called in parallel - with postLogin() first.
How can I make postMyData() execute postLogin() first, wait for success or failure, followed by postData() on success ?
Note: postLogin() will update apiClient with the new token inside storeAccessToken(). I now see that postData() doesn't use a reference to the new apiClient. It's important that postData() will use the new apiClient that's instantiated within storeAccessToken()
Sorry for the newbie question :-(
it turned out that Completable.andThen(Single) works very well to serialize code execution. Unfortunately, I didn't (half asleep) realize that only code within the create() method was actually scheduled.
my code below answers the problem I had (these are both in LAYER-B):
public Single<ResponseLogin> postLogin(ReqLoginData loginData) {
return Single.create(subscriber -> {
Log.d(TAG, "using apiClient "+apiClient.toString());
apiClient.postLogin(loginData)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.isSuccessful() && response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
});
});
}
public Single<ResponseData> postData(ReqData data, Long id) {
return Single.create(subscriber -> {
Log.d(TAG, "using apiClient "+apiClient.toString());
apiClient.postData(id, data)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(response -> {
if(response.body() != null) {
if (!subscriber.isDisposed()) subscriber.onSuccess(response.body());
} else {
if (!subscriber.isDisposed()) subscriber.onError(new Throwable(response.message()));
}
}, throwable -> {
throwable.printStackTrace();
if(!subscriber.isDisposed()) subscriber.onError(throwable);
});
});
}
Related
I am using latest version of Vaadin.
Intended: want to catch an event if AppNavItem (with child elements) is clicked (expanded, toggled).
Code:
#JsModule("#vaadin-component-factory/vcf-nav")
#Tag("vcf-nav-item")
public class AppNavItem extends Component {
public AppNavItem(String label) {
setLabel(label);
}
public AppNavItem setExpanded(boolean value) {
if (value) {
getElement().setAttribute("expanded", "");
} else {
getElement().removeAttribute("expanded");
}
return this;
}
public AppNavItem setIcon(Component icon) {
icon.getElement().setAttribute("slot", "prefix");
int iconElementIndex = getIconElementIndex();
if (iconElementIndex != -1) {
getElement().setChild(iconElementIndex, icon.getElement());
} else {
getElement().appendChild(icon.getElement());
}
return this;
}
}
AppNavItem myItem = new AppNavItem("Project");
myItem.addAttachListener(e -> {
System.out.println(e.toString()); // works on page load as expected !
});
//projectParent.onEnabledStateChanged(false); // does not work
//projectParent.onEnabledStateChanged(true); // does not work
myItem.getElement().addEventListener("onchange", e -> {
System.out.println(e.getType()); // does not work
});
myItem.getElement().addPropertyChangeListener("expanded","onchange", e -> {
System.out.println(e.getPropertyName()); // does not work
});
myItem.getElement().addEventListener("onchange", e -> {
System.out.println(e.getType());
});
myItem.getElement().addPropertyChangeListener("expanded","onchange", e -> {
System.out.println(e.getPropertyName()); // does not work
});
myItem.getElement().addPropertyChangeListener("expanded", e -> {
System.out.println(e.getPropertyName()); // does not work
});
myItem.addItem(...);
I tried several eventTypes like: click, onclick, change, onchange, ontoggle, ...
Unfortunately, almost nothing works, see comment.
What am I doing wrong ?
I expect to catch an event
This is the method used for database connection and obtain results:
public Future<String> getDatabaseUsers(JDBCClient client) {
return Future.future(pHandler -> {
client.getConnection(res -> {
if (res.succeeded()) {
SQLConnection con = res.result();
con.query("select u.id, u.name from users u", rHandler -> {
String data;
if (rHandler.succeeded()) {
data = Json.encode(rHandler.result().getResults());
} else {
data = "Database execution error";
}
con.close();
pHandler.complete(data);
});
} else {
pHandler.complete("Cannot connect to database");
}
});
});
}
This is the caller method:
private void handleRequest(RoutingContext routingContext, JDBCClient client,
Handler<List<String>> resultHandler) {
routingContext.vertx().<String>executeBlocking(pHandler -> {
pHandler.complete(getDatabaseUsers(client).result());
}, ar -> {
List<String> responses = new ArrayList<>();
if (ar.succeeded()) {
responses.add(ar.result());
System.out.println(Json.encode(responses)); // Null here
}
resultHandler.handle(responses);
});
}
The resultHandler object is used to add more responses from other processes; but this is not the problem actually.
And this is the endpoint:
router.get("/db").handler(ctx -> handleRequest(
ctx, client, (list) -> ctx.response()
.putHeader("Content-Type", "text/plain")
.end(Json.encode(list))));
The problem with this code, is that service response is [null] and the database method is not accomplished yet.
So, what should I do to wait for database response and then send the response to the client?
There are a number of issues with this code:
getDatabaseUsers swallows errors. You probably want to do pHandler.fail(res.failure()); or something similar.
This code: pHandler.complete(getDatabaseUsers(client).result()); is not doing what you think it's doing. result() doesn't block, so you complete your future with another unfishined future.
What you actually want is the reverse:
getDatabaseUsers(client).handle((r) -> { // This is called when the futures actually completes
if (r.succeeded()) {
pHandler.complete(r.result());
}
...
});
I would really recommend going over this guide, as it covers exactly your case.
I always return http 200 back and define my own error code. If using Promise, I could reject a response which contains customized error. How can I do it using Observable? I do it like this and it works, but is it a correct way?
My interceptor:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).flatMap((event: any) => {
if (event instanceof HttpResponse) {
if (event.body.status) {
if (event.body.status === 'NOK') {
return Observable.throw(event.body);
}
}
}
return Observable.create(observer => observer.next(event));
})}
My provider:
private handleErrorObservable(error: Response | any) {
return Observable.throw(error.message || error);
}
constructor(public http: HttpClient) {
}
signIn(params: any) {
...(some more codes here)
return this.http.post(this.apiUrl + func, requestData, options).map(
(response) => {
//do something with the response
return response;
}).catch(this.handleErrorObservable);
}
My component:
if (form.valid) {
this.auth.signIn(this.login).subscribe(val => {
//console.log(val);
this.navCtrl.setRoot('WebPage');
}, err => {
// error handling here
})
}
I am trying to implement a catch for 401 responses and tried obtaining a refresh token based on Angular 4 Interceptor retry requests after token refresh. I was trying to implement the same thing, but I never was able to Retry that request, and I am really not sure if that is the best approach to apply the refresh token strategy.
Here is my code:
#Injectable()
export class AuthInterceptorService implements HttpInterceptor {
public authService;
refreshTokenInProgress = false;
tokenRefreshedSource = new Subject();
tokenRefreshed$ = this.tokenRefreshedSource.asObservable();
constructor(private router: Router, private injector: Injector) { }
authenticateRequest(req: HttpRequest<any>) {
const token = this.authService.getToken();
if (token != null) {
return req.clone({
headers: req.headers.set('Authorization', `Bearer ${token.access_token}`)
});
}
else {
return null;
}
}
refreshToken() {
if (this.refreshTokenInProgress) {
return new Observable(observer => {
this.tokenRefreshed$.subscribe(() => {
observer.next();
observer.complete();
});
});
} else {
this.refreshTokenInProgress = true;
return this.authService.refreshToken()
.do(() => {
this.refreshTokenInProgress = false;
this.tokenRefreshedSource.next();
}).catch(
(error) => {
console.log(error);
}
);
}
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authService = this.injector.get(AuthenticationService);
request = this.authenticateRequest(request);
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
return this.refreshToken()
.switchMap(() => {
request = this.authenticateRequest(request);
console.log('*Repeating httpRequest*', request);
return next.handle(request);
})
.catch(() => {
return Observable.empty();
});
}
}
});
}
}
The issue is that SwitchMap is never reached in...
if (err.status === 401) {
return this.refreshToken()
.switchMap(() => {
and the do operator as well...
return this.authService.refreshToken()
.do(() => {
so that took me to my authService refreshToken method...
refreshToken() {
let refreshToken = this.getToken();
refreshToken.grant_type = 'refresh_token';
refreshToken.clientId = environment.appSettings.clientId;
return this.apiHelper.httpPost(url, refreshToken, null)
.map
(
response => {
this.setToken(response.data, refreshToken.email);
return this.getToken();
}
).catch(error => {
return Observable.throw('Please insert credentials');
});
}
}
It returns a mapped observable, and I know it needs a subscription if I replaced the do in...
return this.authService.refreshToken()
.do(() => {
With subscribe I'll break the observable chain I guess. I am lost and I've playing with this for a long time without a solution. :D
I'm glad that you like my solution. I'm going to put just the final solution here but if anybody wants to know the process that I fallowed go here: Refresh Token OAuth Authentication Angular 4+
Ok, First I created a Service to save the state of the refresh token request and Observable to know when the request is done.
This is my Service:
#Injectable()
export class RefreshTokenService {
public processing: boolean = false;
public storage: Subject<any> = new Subject<any>();
public publish(value: any) {
this.storage.next(value);
}
}
I noticed that It was better if I have two Interceptors one to refresh the token and handle that and one to put the Authorization Header if exist.
This the Interceptor for Refresh the Token:
#Injectable()
export class RefreshTokenInterceptor implements HttpInterceptor {
constructor(private injector: Injector, private tokenService: RefreshTokenService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(OAuthService);
if (!auth.hasAuthorization() && auth.hasAuthorizationRefresh() && !this.tokenService.processing && request.url !== AUTHORIZE_URL) {
this.tokenService.processing = true;
return auth.refreshToken().flatMap(
(res: any) => {
auth.saveTokens(res);
this.tokenService.publish(res);
this.tokenService.processing = false;
return next.handle(request);
}
).catch(() => {
this.tokenService.publish({});
this.tokenService.processing = false;
return next.handle(request);
});
} else if (request.url === AUTHORIZE_URL) {
return next.handle(request);
}
if (this.tokenService.processing) {
return this.tokenService.storage.flatMap(
() => {
return next.handle(request);
}
);
} else {
return next.handle(request);
}
}
}
So here I'm waiting to the refresh token to be available or fails and then I release the request that needs the Authorization Header.
This is the Interceptor to put the Authorization Header:
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(OAuthService);
let req = request;
if (auth.hasAuthorization()) {
req = request.clone({
headers: request.headers.set('Authorization', auth.getHeaderAuthorization())
});
}
return next.handle(req).do(
() => {},
(error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
auth.logOut();
}
}
});
}
}
And my main module is something like this:
#NgModule({
imports: [
...,
HttpClientModule
],
declarations: [
...
],
providers: [
...
OAuthService,
AuthService,
RefreshTokenService,
{
provide: HTTP_INTERCEPTORS,
useClass: RefreshTokenInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
Please any feedback will be welcome and if I'm doning something wrong tell me. I'm testing with Angular 4.4.6 but I don't know if it work on angular 5, I think should work.
Below interceptors do this task for you
import {
throwError as observableThrowError,
Observable,
Subject,
EMPTY,
} from 'rxjs';
import { catchError, switchMap, tap, finalize } from 'rxjs/operators';
import { Injectable } from '#angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpSentEvent,
HttpHeaderResponse,
HttpProgressEvent,
HttpResponse,
HttpUserEvent,
HttpErrorResponse,
} from '#angular/common/http';
import { StoreService } from './store.service';
import { ApiService } from './api.service';
export const tokenURL = '/315cfb2a-3fdf-48c3-921f-1d5209cb7861'; //copied from api service
#Injectable()
export class SessionInterceptorService implements HttpInterceptor {
isRefreshingToken: boolean = false;
cachedRequests = [];
tokenSubject: Subject<string> = new Subject<string>();
constructor(
private readonly store: StoreService,
private readonly ApiService: ApiService
) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<
| HttpSentEvent
| HttpHeaderResponse
| HttpProgressEvent
| HttpResponse<any>
| HttpUserEvent<any>
> {
let urlPresentIndex = this.cachedRequests.findIndex(
(httpRequest) => httpRequest.url == req.url
);
if (this.isRefreshingToken && !req.url.endsWith(tokenURL)) {
// check if unique url to be added in cachedRequest
if (urlPresentIndex == -1) {
this.cachedRequests.push(req);
return this.tokenSubject.pipe(
switchMap(() => next.handle(req)),
tap((v) => {
// delete request from catchedRequest if api gets called
this.cachedRequests.splice(
this.cachedRequests.findIndex(
(httpRequest) => httpRequest.url == req.url
),
1
);
return EMPTY;
})
);
} else {
//already in cached request array
return EMPTY;
}
}
return next.handle(this.updateHeader(req)).pipe(
catchError((error) => {
console.log(error);
if (error instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>error).status) {
case 400:
return this.handle400Error(error);
case 403 || 401:
if (req.url.endsWith(tokenURL)) {
return observableThrowError(error);
} else {
this.cachedRequests.push(req);
return this.handle401Error(req, next);
}
default:
return observableThrowError(error);
}
} else {
return observableThrowError(error);
}
})
);
}
handle400Error(error) {
if (
error &&
error.status === 400 &&
error.error &&
error.error.error === 'invalid_grant'
) {
// If we get a 400 and the error message is 'invalid_grant', the token is no longer valid so logout.
return this.logout();
}
return observableThrowError(error);
}
handle401Error(req: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
return this.ApiService.refreshToken().pipe(
switchMap((newToken: string) => {
if (newToken) {
this.store.updateAccessToken(newToken);
this.tokenSubject.next(newToken);
return next.handle(this.updateHeader(this.cachedRequests[0]));
}
// If we don't get a new token, we are in trouble so logout.
return this.logout();
}),
catchError((error) => {
// If there is an exception calling 'refreshToken', bad news so logout.
return this.logout();
}),
finalize(() => {
this.isRefreshingToken = false;
})
);
}
}
logout() {
console.log('logging it out');
// Route to the login page (implementation up to you)
return observableThrowError('');
}
/*
This method is append token in HTTP request'.
*/
updateHeader(req) {
const authToken = this.store.getAccessToken();
console.log(authToken);
req = req.clone({
headers: req.headers.set('X-RapidAPI-Key', `${authToken}`),
});
return req;
}
}
For more details you can read my medium article Token-Refresh-Interceptor-retry-failed-Requests
Check it out, how it works stackblitz
Excellent Angular 2/Material Design framework, Teradata Covalent, provides a RESTService abstract class that wraps REST api calls here:
https://teradata.github.io/covalent/#/components/http
Code to incorporate the extension is easy, as follows:
export class CustomRESTService extends RESTService<any> {
constructor(private _http: Http /* or HttpInterceptorService */) {
super(_http, {
baseUrl: 'www.api.com',
path: '/path/to/endpoint',
headers: new Headers(),
dynamicHeaders: () => new Headers(),
transform: (res: Response): any => res.json(),
});
}
}
The "update" method in the RESTService abstract class is shown here:
public update(id: string | number, obj: T, transform?: IRestTransform): Observable<any> {
let requestOptions: RequestOptionsArgs = this.buildRequestOptions();
let request: Observable<Response> = this.http.patch(this.buildUrl(id), obj, requestOptions);
return request.map((res: Response) => {
if (res.status === 200) {
if (transform) {
return transform(res);
}
return this.transform(res);
} else {
return res;
}
}).catch((error: Response) => {
return new Observable<any>((subscriber: Subscriber<any>) => {
try {
subscriber.error(this.transform(error));
} catch (err) {
subscriber.error(error);
}
});
});
}
My question is: if the update method of the abstract class throws an exception, how can that be captured in the CustomRESTService class? I.e., what Typescript code might one use to display an error in the UI?
Thank you.
First thing's first - Why would you want to catch it inside the rest client and not inside the app's logic?
Assuming you have some good reason for doing that (some other infrastructure code that you're running in the CustomRESTClient class), I would override the update function and implement error handling there.
A simple example without observables:
abstract class Base {
update(n:number):number {
return n;
}
test():bool;
}
class Child extends Base {
update(n:number):number {
return super.update(n)*2;
}
test():bool {
return true;
}
}