Skip to content

Commit d75ab37

Browse files
authored
Merge pull request DSpace#1407 from 4Science/DSC-287-Show-an-error-page-if-the-REST-API-is-not-available
Show an error page if the rest api is not available
2 parents 9310d6e + 98bdc59 commit d75ab37

13 files changed

Lines changed: 234 additions & 15 deletions

src/app/app-routing-paths.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ export function getPageNotFoundRoute() {
8989
return `/${PAGE_NOT_FOUND_PATH}`;
9090
}
9191

92+
export const INTERNAL_SERVER_ERROR = '500';
93+
94+
export function getPageInternalServerErrorRoute() {
95+
return `/${INTERNAL_SERVER_ERROR}`;
96+
}
97+
9298
export const INFO_MODULE_PATH = 'info';
9399
export function getInfoModulePath() {
94100
return `/${INFO_MODULE_PATH}`;

src/app/app-routing.module.ts

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ import {
1111
FORBIDDEN_PATH,
1212
FORGOT_PASSWORD_PATH,
1313
INFO_MODULE_PATH,
14+
INTERNAL_SERVER_ERROR,
15+
LEGACY_BITSTREAM_MODULE_PATH,
1416
PROFILE_MODULE_PATH,
1517
REGISTER_PATH,
18+
REQUEST_COPY_MODULE_PATH,
1619
WORKFLOW_ITEM_MODULE_PATH,
17-
LEGACY_BITSTREAM_MODULE_PATH, REQUEST_COPY_MODULE_PATH,
1820
} from './app-routing-paths';
1921
import { COLLECTION_MODULE_PATH } from './collection-page/collection-page-routing-paths';
2022
import { COMMUNITY_MODULE_PATH } from './community-page/community-page-routing-paths';
@@ -26,14 +28,25 @@ import { SiteRegisterGuard } from './core/data/feature-authorization/feature-aut
2628
import { ThemedPageNotFoundComponent } from './pagenotfound/themed-pagenotfound.component';
2729
import { ThemedForbiddenComponent } from './forbidden/themed-forbidden.component';
2830
import { GroupAdministratorGuard } from './core/data/feature-authorization/feature-authorization-guard/group-administrator.guard';
31+
import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component';
32+
import { ServerCheckGuard } from './core/server-check/server-check.guard';
2933

3034
@NgModule({
3135
imports: [
32-
RouterModule.forRoot([{
33-
path: '', canActivate: [AuthBlockingGuard],
36+
RouterModule.forRoot([
37+
{ path: INTERNAL_SERVER_ERROR, component: ThemedPageInternalServerErrorComponent },
38+
{
39+
path: '',
40+
canActivate: [AuthBlockingGuard],
41+
canActivateChild: [ServerCheckGuard],
3442
children: [
3543
{ path: '', redirectTo: '/home', pathMatch: 'full' },
36-
{ path: 'reload/:rnd', component: ThemedPageNotFoundComponent, pathMatch: 'full', canActivate: [ReloadGuard] },
44+
{
45+
path: 'reload/:rnd',
46+
component: ThemedPageNotFoundComponent,
47+
pathMatch: 'full',
48+
canActivate: [ReloadGuard]
49+
},
3750
{
3851
path: 'home',
3952
loadChildren: () => import('./home-page/home-page.module')
@@ -89,7 +102,8 @@ import { GroupAdministratorGuard } from './core/data/feature-authorization/featu
89102
.then((m) => m.ItemPageModule),
90103
canActivate: [EndUserAgreementCurrentUserGuard]
91104
},
92-
{ path: 'entities/:entity-type',
105+
{
106+
path: 'entities/:entity-type',
93107
loadChildren: () => import('./item-page/item-page.module')
94108
.then((m) => m.ItemPageModule),
95109
canActivate: [EndUserAgreementCurrentUserGuard]
@@ -133,12 +147,12 @@ import { GroupAdministratorGuard } from './core/data/feature-authorization/featu
133147
{
134148
path: 'login',
135149
loadChildren: () => import('./login-page/login-page.module')
136-
.then((m) => m.LoginPageModule),
150+
.then((m) => m.LoginPageModule)
137151
},
138152
{
139153
path: 'logout',
140154
loadChildren: () => import('./logout-page/logout-page.module')
141-
.then((m) => m.LogoutPageModule),
155+
.then((m) => m.LogoutPageModule)
142156
},
143157
{
144158
path: 'submit',
@@ -178,7 +192,7 @@ import { GroupAdministratorGuard } from './core/data/feature-authorization/featu
178192
},
179193
{
180194
path: INFO_MODULE_PATH,
181-
loadChildren: () => import('./info/info.module').then((m) => m.InfoModule),
195+
loadChildren: () => import('./info/info.module').then((m) => m.InfoModule)
182196
},
183197
{
184198
path: REQUEST_COPY_MODULE_PATH,
@@ -192,17 +206,18 @@ import { GroupAdministratorGuard } from './core/data/feature-authorization/featu
192206
{
193207
path: 'statistics',
194208
loadChildren: () => import('./statistics-page/statistics-page-routing.module')
195-
.then((m) => m.StatisticsPageRoutingModule),
209+
.then((m) => m.StatisticsPageRoutingModule)
196210
},
197211
{
198212
path: ACCESS_CONTROL_MODULE_PATH,
199213
loadChildren: () => import('./access-control/access-control.module').then((m) => m.AccessControlModule),
200214
canActivate: [GroupAdministratorGuard],
201215
},
202216
{ path: '**', pathMatch: 'full', component: ThemedPageNotFoundComponent },
203-
]}
204-
],{
205-
onSameUrlNavigation: 'reload',
217+
]
218+
}
219+
], {
220+
onSameUrlNavigation: 'reload',
206221
})
207222
],
208223
exports: [RouterModule],

src/app/app.module.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ import { ThemedFooterComponent } from './footer/themed-footer.component';
5454
import { ThemedBreadcrumbsComponent } from './breadcrumbs/themed-breadcrumbs.component';
5555
import { ThemedHeaderNavbarWrapperComponent } from './header-nav-wrapper/themed-header-navbar-wrapper.component';
5656
import { IdleModalComponent } from './shared/idle-modal/idle-modal.component';
57+
import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component';
58+
import { PageInternalServerErrorComponent } from './page-internal-server-error/page-internal-server-error.component';
5759

5860
import { AppConfig, APP_CONFIG } from '../config/app-config.interface';
5961

@@ -181,7 +183,9 @@ const DECLARATIONS = [
181183
ThemedBreadcrumbsComponent,
182184
ForbiddenComponent,
183185
ThemedForbiddenComponent,
184-
IdleModalComponent
186+
IdleModalComponent,
187+
ThemedPageInternalServerErrorComponent,
188+
PageInternalServerErrorComponent
185189
];
186190

187191
const EXPORTS = [

src/app/core/data/root-data.service.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,5 +106,12 @@ export class RootDataService {
106106
findAllByHref(href: string | Observable<string>, findListOptions: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Root>[]): Observable<RemoteData<PaginatedList<Root>>> {
107107
return this.dataService.findAllByHref(href, findListOptions, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
108108
}
109+
110+
/**
111+
* Set to sale the root endpoint cache hit
112+
*/
113+
invalidateRootCache() {
114+
this.requestService.setStaleByHrefSubstring('server/api');
115+
}
109116
}
110117
/* tslint:enable:max-classes-per-file */
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { ServerCheckGuard } from './server-check.guard';
2+
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
3+
import { take } from 'rxjs/operators';
4+
import { getPageInternalServerErrorRoute } from '../../app-routing-paths';
5+
import { Router } from '@angular/router';
6+
import { RootDataService } from '../data/root-data.service';
7+
import { Root } from '../data/root.model';
8+
import SpyObj = jasmine.SpyObj;
9+
10+
describe('ServerCheckGuard', () => {
11+
let guard: ServerCheckGuard;
12+
let router: SpyObj<Router>;
13+
let rootDataServiceStub: SpyObj<RootDataService>;
14+
15+
rootDataServiceStub = jasmine.createSpyObj('RootDataService', {
16+
findRoot: jasmine.createSpy('findRoot'),
17+
invalidateRootCache: jasmine.createSpy('invalidateRootCache')
18+
});
19+
router = jasmine.createSpyObj('Router', {
20+
navigateByUrl: jasmine.createSpy('navigateByUrl')
21+
});
22+
23+
beforeEach(() => {
24+
guard = new ServerCheckGuard(router, rootDataServiceStub);
25+
});
26+
27+
afterEach(() => {
28+
router.navigateByUrl.calls.reset();
29+
rootDataServiceStub.invalidateRootCache.calls.reset();
30+
rootDataServiceStub.findRoot.calls.reset();
31+
});
32+
33+
it('should be created', () => {
34+
expect(guard).toBeTruthy();
35+
});
36+
37+
describe('when root endpoint has succeeded', () => {
38+
beforeEach(() => {
39+
rootDataServiceStub.findRoot.and.returnValue(createSuccessfulRemoteDataObject$<Root>({} as any));
40+
});
41+
42+
it('should not redirect to error page', () => {
43+
guard.canActivateChild({} as any, {} as any).pipe(
44+
take(1)
45+
).subscribe((canActivate: boolean) => {
46+
expect(canActivate).toEqual(true);
47+
expect(rootDataServiceStub.invalidateRootCache).not.toHaveBeenCalled();
48+
expect(router.navigateByUrl).not.toHaveBeenCalled();
49+
});
50+
});
51+
});
52+
53+
describe('when root endpoint has not succeeded', () => {
54+
beforeEach(() => {
55+
rootDataServiceStub.findRoot.and.returnValue(createFailedRemoteDataObject$<Root>());
56+
});
57+
58+
it('should redirect to error page', () => {
59+
guard.canActivateChild({} as any, {} as any).pipe(
60+
take(1)
61+
).subscribe((canActivate: boolean) => {
62+
expect(canActivate).toEqual(false);
63+
expect(rootDataServiceStub.invalidateRootCache).toHaveBeenCalled();
64+
expect(router.navigateByUrl).toHaveBeenCalledWith(getPageInternalServerErrorRoute());
65+
});
66+
});
67+
});
68+
});
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { Injectable } from '@angular/core';
2+
import { ActivatedRouteSnapshot, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
3+
4+
import { interval, Observable, race } from 'rxjs';
5+
import { map, mergeMapTo, tap } from 'rxjs/operators';
6+
7+
import { RootDataService } from '../data/root-data.service';
8+
import { RemoteData } from '../data/remote-data';
9+
import { getPageInternalServerErrorRoute } from '../../app-routing-paths';
10+
import { getFirstCompletedRemoteData } from '../shared/operators';
11+
12+
@Injectable({
13+
providedIn: 'root'
14+
})
15+
/**
16+
* A guard that checks if root api endpoint is reachable.
17+
* If not redirect to 500 error page
18+
*/
19+
export class ServerCheckGuard implements CanActivateChild {
20+
constructor(private router: Router, private rootDataService: RootDataService) {
21+
}
22+
23+
/**
24+
* True when root api endpoint is reachable.
25+
*/
26+
canActivateChild(
27+
route: ActivatedRouteSnapshot,
28+
state: RouterStateSnapshot): Observable<boolean> {
29+
30+
const uncachedCheck$ = this.rootDataService.findRoot(false);
31+
// fallback observable used if the uncached one hangs and doesn't emit value
32+
const cachedCheck$ = interval(200).pipe(mergeMapTo((this.rootDataService.findRoot())));
33+
34+
return race([uncachedCheck$, cachedCheck$]).pipe(
35+
getFirstCompletedRemoteData(),
36+
map((res: RemoteData<any>) => res.hasSucceeded),
37+
tap((hasSucceeded: boolean) => {
38+
if (!hasSucceeded) {
39+
this.rootDataService.invalidateRootCache();
40+
this.router.navigateByUrl(getPageInternalServerErrorRoute());
41+
}
42+
}),
43+
);
44+
45+
}
46+
}

src/app/core/services/server-response.service.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,8 @@ export class ServerResponseService {
3131
setNotFound(message = 'Not found'): this {
3232
return this.setStatus(404, message);
3333
}
34+
35+
setInternalServerError(message = 'Internal Server Error'): this {
36+
return this.setStatus(500, message);
37+
}
3438
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<div class="page-internal-server-error container">
2+
<h1>500</h1>
3+
<h2><small>{{"500.page-internal-server-error" | translate}}</small></h2>
4+
<br/>
5+
<p>{{"500.help" | translate}}</p>
6+
<br/>
7+
<p class="text-center">
8+
<a routerLink="/home" class="btn btn-primary">{{"500.link.home-page" | translate}}</a>
9+
</p>
10+
</div>

src/app/page-internal-server-error/page-internal-server-error.component.scss

Whitespace-only changes.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { ChangeDetectionStrategy, Component } from '@angular/core';
2+
import { ServerResponseService } from '../core/services/server-response.service';
3+
4+
/**
5+
* This component representing the `PageInternalServer` DSpace page.
6+
*/
7+
@Component({
8+
selector: 'ds-page-internal-server-error',
9+
styleUrls: ['./page-internal-server-error.component.scss'],
10+
templateUrl: './page-internal-server-error.component.html',
11+
changeDetection: ChangeDetectionStrategy.Default
12+
})
13+
export class PageInternalServerErrorComponent {
14+
15+
/**
16+
* Initialize instance variables
17+
*
18+
* @param {ServerResponseService} responseService
19+
*/
20+
constructor(private responseService: ServerResponseService) {
21+
this.responseService.setInternalServerError();
22+
}
23+
}

0 commit comments

Comments
 (0)