Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(platform-server): add an API to transfer state from server
TransferState provides a shared store that is transferred from the server to client. To use it import BrowserTransferStateModule from the client app module and ServerTransferStateModule from the server app module and TransferState will be availabl as an Injectable object.
- Loading branch information
Showing
18 changed files
with
571 additions
and
2 deletions.
There are no files selected for viewing
163 changes: 163 additions & 0 deletions
163
packages/platform-browser/src/browser/transfer_state.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
/** | ||
* @license | ||
* Copyright Google Inc. All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {APP_ID, Injectable, NgModule} from '@angular/core'; | ||
import {DOCUMENT} from '../dom/dom_tokens'; | ||
|
||
export function escapeHtml(text: string): string { | ||
const escapedText: {[k: string]: string} = { | ||
'&': '&', | ||
'"': '"', | ||
'\'': ''', | ||
'<': '<', | ||
'>': '>', | ||
}; | ||
return text.replace(/[&"'<>]/g, s => escapedText[s]); | ||
} | ||
|
||
export function unescapeHtml(text: string): string { | ||
const unescapedText: {[k: string]: string} = { | ||
'&': '&', | ||
'"': '"', | ||
''': '\'', | ||
'<': '<', | ||
'>': '>', | ||
}; | ||
return text.replace(/&[^;]+;/g, s => unescapedText[s]); | ||
} | ||
|
||
/** | ||
* A type-safe key to use with `TransferState`. | ||
* | ||
* Example: | ||
* | ||
* ``` | ||
* const COUNTER_KEY = makeStateKey<number>('counter'); | ||
* let value = 10; | ||
* | ||
* transferState.set(COUNTER_KEY, value); | ||
* ``` | ||
* | ||
* @experimental | ||
*/ | ||
export type StateKey<T> = string & {__not_a_string: never}; | ||
|
||
/** | ||
* Create a `StateKey<T>` that can be used to store value of type T with `TransferState`. | ||
* | ||
* Example: | ||
* | ||
* ``` | ||
* const COUNTER_KEY = makeStateKey<number>('counter'); | ||
* let value = 10; | ||
* | ||
* transferState.set(COUNTER_KEY, value); | ||
* ``` | ||
* | ||
* @experimental | ||
*/ | ||
export function makeStateKey<T>(key: string): StateKey<T> { | ||
return key as StateKey<T>; | ||
} | ||
|
||
/** | ||
* A key value store that is transferred from the application on the server side to the application | ||
* on the client side. | ||
* | ||
* `TransferState` will be available as an injectable token. To use it import | ||
* `ServerTransferStateModule` on the server and `BrowserTransferStateModule` on the client. | ||
* | ||
* The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only | ||
* boolean, number, string, null and non-class objects will be serialized and deserialzied in a | ||
* non-lossy manner. | ||
* | ||
* @experimental | ||
*/ | ||
@Injectable() | ||
export class TransferState { | ||
private store: {[k: string]: {} | undefined} = {}; | ||
private onSerializeCallbacks: {[k: string]: () => {} | undefined} = {}; | ||
|
||
/** @internal */ | ||
static init(initState: {}) { | ||
const transferState = new TransferState(); | ||
transferState.store = initState; | ||
return transferState; | ||
} | ||
|
||
/** | ||
* Get the value corresponding to a key. Return `defaultValue` if key is not found. | ||
*/ | ||
get<T>(key: StateKey<T>, defaultValue: T): T { return this.store[key] as T || defaultValue; } | ||
|
||
/** | ||
* Set the value corresponding to a key. | ||
*/ | ||
set<T>(key: StateKey<T>, value: T): void { this.store[key] = value; } | ||
|
||
/** | ||
* Remove a key from the store. | ||
*/ | ||
remove<T>(key: StateKey<T>): void { delete this.store[key]; } | ||
|
||
/** | ||
* Test whether a key exists in the store. | ||
*/ | ||
hasKey<T>(key: StateKey<T>) { return this.store.hasOwnProperty(key); } | ||
|
||
/** | ||
* Register a callback to provide the value for a key when `toJson` is called. | ||
*/ | ||
onSerialize<T>(key: StateKey<T>, callback: () => T): void { | ||
this.onSerializeCallbacks[key] = callback; | ||
} | ||
|
||
/** | ||
* Serialize the current state of the store to JSON. | ||
*/ | ||
toJson(): string { | ||
// Call the onSerialize callbacks and put those values into the store. | ||
for (const key in this.onSerializeCallbacks) { | ||
if (this.onSerializeCallbacks.hasOwnProperty(key)) { | ||
try { | ||
this.store[key] = this.onSerializeCallbacks[key](); | ||
} catch (e) { | ||
console.warn('Exception in onSerialize callback: ', e); | ||
} | ||
} | ||
} | ||
return JSON.stringify(this.store); | ||
} | ||
} | ||
|
||
export function initTransferState(doc: Document, appId: string) { | ||
// Locate the script tag with the JSON data transferred from the server. | ||
// The id of the script tag is set to the Angular appId + 'state'. | ||
const script = doc.getElementById(appId + '-state'); | ||
let initialState = {}; | ||
if (script && script.textContent) { | ||
try { | ||
initialState = JSON.parse(unescapeHtml(script.textContent)); | ||
} catch (e) { | ||
console.warn('Exception while restoring TransferState for app ' + appId, e); | ||
} | ||
} | ||
return TransferState.init(initialState); | ||
} | ||
|
||
/** | ||
* NgModule to install on the client side while using the `TransferState` to transfer state from | ||
* server to client. | ||
* | ||
* @experimental | ||
*/ | ||
@NgModule({ | ||
providers: [{provide: TransferState, useFactory: initTransferState, deps: [DOCUMENT, APP_ID]}], | ||
}) | ||
export class BrowserTransferStateModule { | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
packages/platform-browser/test/browser/transfer_state_spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
/** | ||
* @license | ||
* Copyright Google Inc. All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
|
||
import {TestBed} from '@angular/core/testing'; | ||
import {BrowserModule, BrowserTransferStateModule, TransferState} from '@angular/platform-browser'; | ||
import {StateKey, escapeHtml, makeStateKey, unescapeHtml} from '@angular/platform-browser/src/browser/transfer_state'; | ||
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; | ||
|
||
export function main() { | ||
function removeScriptTag(doc: Document, id: string) { | ||
const existing = doc.getElementById(id); | ||
if (existing) { | ||
doc.body.removeChild(existing); | ||
} | ||
} | ||
|
||
function addScriptTag(doc: Document, appId: string, data: {}) { | ||
const script = doc.createElement('script'); | ||
const id = appId + '-state'; | ||
script.id = id; | ||
script.setAttribute('type', 'application/json'); | ||
script.textContent = escapeHtml(JSON.stringify(data)); | ||
|
||
// Remove any stale script tags. | ||
removeScriptTag(doc, id); | ||
|
||
doc.body.appendChild(script); | ||
} | ||
|
||
describe('TransferState', () => { | ||
const APP_ID = 'test-app'; | ||
let doc: Document; | ||
|
||
const TEST_KEY = makeStateKey<number>('test'); | ||
const DELAYED_KEY = makeStateKey<string>('delayed'); | ||
|
||
beforeEach(() => { | ||
TestBed.configureTestingModule({ | ||
imports: [ | ||
BrowserModule.withServerTransition({appId: APP_ID}), | ||
BrowserTransferStateModule, | ||
] | ||
}); | ||
doc = TestBed.get(DOCUMENT); | ||
}); | ||
|
||
afterEach(() => { removeScriptTag(doc, APP_ID + '-state'); }); | ||
|
||
it('is initialized from script tag', () => { | ||
addScriptTag(doc, APP_ID, {test: 10}); | ||
const transferState: TransferState = TestBed.get(TransferState); | ||
expect(transferState.get(TEST_KEY, 0)).toBe(10); | ||
}); | ||
|
||
it('is initialized to empty state if script tag not found', () => { | ||
const transferState: TransferState = TestBed.get(TransferState); | ||
expect(transferState.get(TEST_KEY, 0)).toBe(0); | ||
}); | ||
|
||
it('supports adding new keys using set', () => { | ||
const transferState: TransferState = TestBed.get(TransferState); | ||
transferState.set(TEST_KEY, 20); | ||
expect(transferState.get(TEST_KEY, 0)).toBe(20); | ||
expect(transferState.hasKey(TEST_KEY)).toBe(true); | ||
}); | ||
|
||
it('supports removing keys', () => { | ||
const transferState: TransferState = TestBed.get(TransferState); | ||
transferState.set(TEST_KEY, 20); | ||
transferState.remove(TEST_KEY); | ||
expect(transferState.get(TEST_KEY, 0)).toBe(0); | ||
expect(transferState.hasKey(TEST_KEY)).toBe(false); | ||
}); | ||
|
||
it('supports serialization using toJson()', () => { | ||
const transferState: TransferState = TestBed.get(TransferState); | ||
transferState.set(TEST_KEY, 20); | ||
expect(transferState.toJson()).toBe('{"test":20}'); | ||
}); | ||
|
||
it('calls onSerialize callbacks when calling toJson()', () => { | ||
const transferState: TransferState = TestBed.get(TransferState); | ||
transferState.set(TEST_KEY, 20); | ||
|
||
let value = 'initial'; | ||
transferState.onSerialize(DELAYED_KEY, () => value); | ||
value = 'changed'; | ||
|
||
expect(transferState.toJson()).toBe('{"test":20,"delayed":"changed"}'); | ||
}); | ||
}); | ||
|
||
describe('escape/unescape', () => { | ||
it('works with all escaped characters', () => { | ||
const testString = '</script><script>alert(\'Hello&\' + "World");'; | ||
const testObj = {testString}; | ||
const escaped = escapeHtml(JSON.stringify(testObj)); | ||
expect(escaped).toBe( | ||
'{"testString":"</script><script>' + | ||
'alert('Hello&' + \\"World\\");"}'); | ||
|
||
const unescapedObj = JSON.parse(unescapeHtml(escaped)); | ||
expect(unescapedObj['testString']).toBe(testString); | ||
}); | ||
}); | ||
} |
29 changes: 29 additions & 0 deletions
29
packages/platform-server/integrationtest/e2e/transferstate-spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* @license | ||
* Copyright Google Inc. All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {browser, by, element} from 'protractor'; | ||
|
||
import {verifyNoBrowserErrors} from './util'; | ||
|
||
describe('TransferState', function() { | ||
it('should transfer component state', function() { | ||
// Load the page without waiting for Angular since it is not boostrapped automatically. | ||
browser.driver.get(browser.baseUrl + 'transferstate'); | ||
|
||
// Test the contents from the server. | ||
const serverDiv = browser.driver.findElement(by.css('div')); | ||
expect(serverDiv.getText()).toEqual('5'); | ||
|
||
// Bootstrap the client side app and retest the contents | ||
browser.executeScript('doBootstrap()'); | ||
expect(element(by.css('div')).getText()).toEqual('50'); | ||
|
||
// Make sure there were no client side errors. | ||
verifyNoBrowserErrors(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
packages/platform-server/integrationtest/src/transferstate/app.server.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
/** | ||
* @license | ||
* Copyright Google Inc. All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {NgModule} from '@angular/core'; | ||
import {ServerModule, ServerTransferStateModule} from '@angular/platform-server'; | ||
|
||
import {TransferStateModule} from './app'; | ||
import {TransferStateComponent} from './transfer-state.component'; | ||
|
||
@NgModule({ | ||
bootstrap: [TransferStateComponent], | ||
imports: [TransferStateModule, ServerModule, ServerTransferStateModule], | ||
}) | ||
export class TransferStateServerModule { | ||
} |
23 changes: 23 additions & 0 deletions
23
packages/platform-server/integrationtest/src/transferstate/app.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* @license | ||
* Copyright Google Inc. All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import {NgModule} from '@angular/core'; | ||
import {BrowserModule, BrowserTransferStateModule} from '@angular/platform-browser'; | ||
|
||
import {TransferStateComponent} from './transfer-state.component'; | ||
|
||
@NgModule({ | ||
declarations: [TransferStateComponent], | ||
bootstrap: [TransferStateComponent], | ||
imports: [ | ||
BrowserModule.withServerTransition({appId: 'ts'}), | ||
BrowserTransferStateModule, | ||
], | ||
}) | ||
export class TransferStateModule { | ||
} |
Oops, something went wrong.