Skip to content

Commit

Permalink
feat(ssr): added serialiser and safety methods
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewcourtice committed Dec 2, 2022
1 parent bfa3764 commit b7abfd5
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 10 deletions.
5 changes: 5 additions & 0 deletions plugins/ssr/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import {
SSRSerializer,
} from './types';

export const SENDER = 'plugin:ssr';
export const SERIALIZER: SSRSerializer = snapshot => JSON.stringify(snapshot);

export const MUTATIONS = {
init: 'plugin:ssr:init',
Expand Down
23 changes: 13 additions & 10 deletions plugins/ssr/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
MUTATIONS,
SENDER,
SERIALIZER,
} from './constants';

import {
Expand All @@ -15,13 +16,14 @@ import {
objectOverwrite,
} from '@harlem/utilities';

declare global {
interface Window {
__harlemState: Record<string, any>;
}
}
import type {
SSRData,
SSRSerializer,
} from './types';

export * from './types';

const snapshot: Record<string, any> = {};
const snapshot: SSRData = {};

function onStoreEvent(stores: InternalStores, payload: EventPayload | undefined, callback: (store: InternalStore) => void): void {
if (!payload) {
Expand All @@ -38,15 +40,15 @@ function onStoreEvent(stores: InternalStores, payload: EventPayload | undefined,
/**
* Generate a script required to transfer state from server to client
*/
export function getBridgingScript(): string {
return `window.__harlemState = ${JSON.stringify(snapshot)};`;
export function getBridgingScript(serializer: SSRSerializer = SERIALIZER): string {
return `window.__harlemState = ${serializer(snapshot)};`;
}

/**
* Generate a script block required to transfer state from server to client
*/
export function getBridgingScriptBlock(): string {
return `<script>${getBridgingScript()}</script>`;
export function getBridgingScriptBlock(serializer: SSRSerializer = SERIALIZER): string {
return `<script>${getBridgingScript(serializer)}</script>`;
}

/**
Expand Down Expand Up @@ -74,6 +76,7 @@ export function createClientSSRPlugin(): HarlemPlugin {
eventEmitter.on(EVENTS.ssr.initClient, payload => onStoreEvent(stores, payload, store => {
if (store.name in data) {
store.write(MUTATIONS.init, SENDER, state => objectOverwrite(state, data[store.name]));
delete data[store.name];
}
}));
};
Expand Down
12 changes: 12 additions & 0 deletions plugins/ssr/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {
BaseState,
} from '@harlem/core';

declare global {
interface Window {
__harlemState: SSRData;
}
}

export type SSRData = Record<string, BaseState>;
export type SSRSerializer = (snapshot: SSRData) => string;

0 comments on commit b7abfd5

Please sign in to comment.