Skip to content

Commit

Permalink
use state transfer for ssr (#241)
Browse files Browse the repository at this point in the history
## Why?

- During Angular universal application loading, the API requests were running even if the data was already rendered from the server.
- The router was flickering on angular universal first page load.
- Product detail page shown as blank when data is fetching from api.

## This change addresses the need by:

- added state transfer interceptor to check for stored data in state and avoid api calls if data already sent from SSR server
- Fixed route resolve issue for product detail
- Bug fix for app route flicker on universal boot. Fix shown in this [angular Issue.](angular/angular#15716 (comment))
  • Loading branch information
pkrawat1 committed Aug 21, 2018
1 parent bdcc700 commit 9b06906
Show file tree
Hide file tree
Showing 68 changed files with 379 additions and 260 deletions.
2 changes: 1 addition & 1 deletion .firebaserc
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
"default": "angularspree",
"staging": "angularspree"
}
}
}
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"node_modules": true,
"bin": true,
"obj": true,
"dist": true,
"dist": false,
"Properties": true,
".vs": true,
"*.csproj": true,
Expand Down
12 changes: 5 additions & 7 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,20 @@
"input": "src",
"output": "/"
},
{
"glob": "service-worker.js",
"input": "src",
"output": "/"
},
{
"glob": "manifest.json",
"input": "src",
"output": "/"
},
"src/manifest.json",
"src/manifest.json"
],
"styles": [
"node_modules/font-awesome/css/font-awesome.css",
"src/styles.scss"
],
"scripts": [],
"serviceWorker": true
"serviceWorker": false
},
"configurations": {
"mock-ng-spree": {
Expand Down Expand Up @@ -97,6 +93,7 @@
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"serviceWorker": false,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
Expand Down Expand Up @@ -218,6 +215,7 @@
"input": "src",
"output": "/"
},
"src/manifest.json",
"src/manifest.json"
]
}
Expand Down Expand Up @@ -271,4 +269,4 @@
"prefix": "app"
}
}
}
}
55 changes: 35 additions & 20 deletions ngsw-config.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
"dataGroups": [
{
"name": "api-performance",
"urls": [
"/products"
],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 100,
"maxAge": "3d"
}
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
],
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}
}]
}
]
}
18 changes: 3 additions & 15 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,29 @@
"license": "MIT",
"scripts": {
"ng": "./node_modules/@angular/cli/bin/ng",

"start:mock-ng-spree": "ng serve --configuration=mock-ng-spree",

"e2e:dev-ng-spree": "ng e2e --configuration=dev-ng-spree",
"lint:dev-ng-spree": "ng lint --configuration=dev-ng-spree",
"test:dev-ng-spree": "ng test --configuration=dev-ng-spree",
"build:dev-ng-spree": "ng build --configuration=dev-ng-spree",
"start:dev-ng-spree": "ng serve --configuration=dev-ng-spree",
"build:prod-ng-spree": "ng build --configuration=prod-ng-spree",


"e2e:dev-custom": "ng e2e --configuration=dev-custom",
"lint:dev-custom": "ng lint --configuration=dev-custom",
"test:dev-custom": "ng test --configuration=dev-custom",
"build:dev-custom": "ng build --configuration=dev-custom",
"start:dev-custom": "ng serve --configuration=dev-custom",
"build:prod-custom": "ng build --configuration=prod-custom",

"compodoc": "./node_modules/.bin/compodoc -p src/tsconfig.app.json -d docs/",

"sw": "sw-precache --root=dist --config=sw-precache-config.js",

"bundle-report": "webpack-bundle-analyzer dist/stats.json",

"static-serve": "cd dist/browser && live-server --port=4200 --host=localhost --entry-file=/index.html",

"build:ssr:prod-custom": "npm run build:client-and-server-bundles:prod-custom && npm run webpack:server",
"build:ssr:prod-ng-spree": "npm run build:client-and-server-bundles:prod-ng-spree && npm run webpack:server",

"start:ssr:prod-custom": "npm run build:ssr:prod-custom && node dist/server",
"start:ssr:prod-ng-spree": "npm run build:ssr:prod-ng-spree && node dist/server",

"build:client-and-server-bundles:prod-custom": "npm run build:prod-custom && ng run angularspree:server:prod-custom",
"build:client-and-server-bundles:prod-ng-spree": "npm run build:prod-ng-spree && ng run angularspree:server:prod-ng-spree",

"webpack:server": "webpack --config webpack.server.config.js --progress --colors"
},
"private": true,
Expand All @@ -52,7 +40,7 @@
"@angular/platform-browser": "^6.1.1",
"@angular/platform-browser-dynamic": "^6.1.1",
"@angular/platform-server": "^6.1.1",
"@angular/pwa": "^0.7.2",
"@angular/pwa": "^0.7.4",
"@angular/router": "^6.1.1",
"@angular/service-worker": "^6.1.1",
"@ngrx/core": "^1.2.0",
Expand Down Expand Up @@ -89,8 +77,8 @@
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.7.2",
"@angular/cli": "^6.1.2",
"@angular-devkit/build-angular": "^0.7.4",
"@angular/cli": "^6.1.4",
"@angular/compiler-cli": "^6.1.1",
"@angular/language-service": "^6.1.1",
"@angularclass/hmr": "^2.1.3",
Expand Down
4 changes: 2 additions & 2 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { ToastrModule } from 'ngx-toastr';
CheckoutFooterComponent
],
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: AppPreloadingStrategy }),
RouterModule.forRoot(routes, { preloadingStrategy: AppPreloadingStrategy, initialNavigation: 'enabled' }),
StoreModule.forRoot(reducers, { metaReducers }),

/**
Expand Down Expand Up @@ -77,7 +77,7 @@ import { ToastrModule } from 'ngx-toastr';
}),
CoreModule,
SharedModule,
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
],
providers: [AppPreloadingStrategy],
bootstrap: [AppComponent]
Expand Down
1 change: 0 additions & 1 deletion src/app/checkout/cart/cart.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { EffectsModule } from '@ngrx/effects';
import { CommonModule } from '@angular/common';
import { CartComponent } from './cart.component';
import { NgModule } from '@angular/core';
Expand Down
4 changes: 4 additions & 0 deletions src/app/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { TransferStateInterceptor } from './interceptors/transfer-state.interceptor';
import { TransferStateService } from './services/transfer-state.service';
import { CheckoutEffects } from './../checkout/effects/checkout.effects';
import { CheckoutActions } from './../checkout/actions/checkout.actions';
import { CheckoutService } from './services/checkout.service';
Expand Down Expand Up @@ -63,6 +65,8 @@ import { CanActivateViaAuthGuard } from './guards/auth.guard';
UserActions,
UserService,
CanActivateViaAuthGuard,
{provide: HTTP_INTERCEPTORS, useClass: TransferStateInterceptor, multi: true},
TransferStateService,
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
]
})
Expand Down
45 changes: 45 additions & 0 deletions src/app/core/interceptors/transfer-state.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { tap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse
} from '@angular/common/http';
import { TransferStateService } from '../services/transfer-state.service';

@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {
constructor(private transferStateService: TransferStateService) {
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
/**
* Skip this interceptor if the request method isn't GET.
*/
if (req.method !== 'GET') {
return next.handle(req);
}

const cachedResponse = this.transferStateService.getCache(req.url);
if (cachedResponse) {
// A cached response exists which means server set it before. Serve it instead of forwarding
// the request to the next handler.
return of(new HttpResponse<any>({ body: cachedResponse }));
}

/**
* No cached response exists. Go to the network, and cache
* the response when it arrives.
*/
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.transferStateService.setCache(req.url, event.body);
}
})
);
}
}
10 changes: 3 additions & 7 deletions src/app/core/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { of as observableOf, Observable } from 'rxjs';
import { of as observableOf, Observable, throwError, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
Expand Down Expand Up @@ -30,7 +30,7 @@ export class AuthService {
private toastrService: ToastrService,
private router: Router,
@Inject(PLATFORM_ID) private platformId: any
) {}
) { }

/**
*
Expand Down Expand Up @@ -141,11 +141,7 @@ export class AuthService {
authorized(): Observable<any> {
return this.http
.get('auth/authenticated')
.pipe(map((res: Response) => res));
// catch should be handled here with the http observable
// so that only the inner obs dies and not the effect Observable
// otherwise no further login requests will be fired
// MORE INFO https://youtu.be/3LKMwkuK0ZE?t=24m29s
.pipe(catchError(error => of(error.error)));
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/app/core/services/product.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class ProductService {
getProduct(id: string): Observable<Product> {
return this.http
.get<{ data: CJsonApi }>(
`api/v1/products/${id}?data_set=large&${+new Date()}`
`api/v1/products/${id}?data_set=large&${+new Date().getDate()}`
)
.pipe(
map(resp => {
Expand Down Expand Up @@ -148,7 +148,7 @@ export class ProductService {
getproductsByKeyword(keyword: string): Observable<any> {
return this.http
.get<{ data: CJsonApi[]; pagination: Object }>(
`api/v1/products?${keyword}&per_page=20&data_set=small&${+new Date()}`
`api/v1/products?${keyword}&per_page=20&data_set=small&${+new Date().getDate()}`
)
.pipe(
map(resp => {
Expand Down
48 changes: 48 additions & 0 deletions src/app/core/services/transfer-state.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { isPlatformBrowser } from '@angular/common';

/**
* Keep caches (makeStateKey) into it in each `setCache` function call
* @type {any[]}
*/
const transferStateCache: String[] = [];

@Injectable()
export class TransferStateService {
constructor(private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object,
// @Inject(APP_ID) private _appId: string
) {
}

/**
* Set cache only when it's running on server
* @param {string} key
* @param data Data to store to cache
*/
setCache(key: string, data: any) {
if (!isPlatformBrowser(this.platformId)) {
transferStateCache[key] = makeStateKey<any>(key);
this.transferState.set(transferStateCache[key], data);
}
}


/**
* Returns stored cache only when it's running on browser
* @param {string} key
* @returns {any} cachedData
*/
getCache(key: string): any {
if (isPlatformBrowser(this.platformId)) {
const cachedData: any = this.transferState['store'][key];
/**
* Delete the cache to request the data from network next time which is the
* user's expected behavior
*/
delete this.transferState['store'][key];
return cachedData;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ export class ContentHeaderComponent implements OnInit {
}

ngOnInit() {
if (window.screen.width <= 768) {
if (isPlatformBrowser(this.platformId)) {
if (isPlatformBrowser(this.platformId)) {
if (window.screen.width <= 768) {
this.screenWidth = window.screen.width;
}
}
Expand Down
1 change: 0 additions & 1 deletion src/app/home/home.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,4 @@ import { CategoryPageComponent } from './category-page/category-page.component';
export const HomeRoutes = [
{ path: 'search', component: HomeComponent },
{ path: 'c/:number', component: CategoryPageComponent},

];
1 change: 0 additions & 1 deletion src/app/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { ProductState } from './product/reducers/product-state';
import { AuthState } from './auth/reducers/auth.state';
import { UserState } from './user/reducers/user.state';
import { CheckoutState } from './checkout/reducers/checkout.state';
import { SearchState } from './home/reducers/search.state';

// This should hold the AppState interface
// Ideally importing all the substate for the application
Expand Down
5 changes: 0 additions & 5 deletions src/app/landing/brands-page/brands-page.component.html

This file was deleted.

Loading

0 comments on commit 9b06906

Please sign in to comment.