Skip to content

Commit

Permalink
chore: cleanup hydration name
Browse files Browse the repository at this point in the history
  • Loading branch information
damassi committed Nov 24, 2024
1 parent ea097ab commit ed0585c
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 69 deletions.
2 changes: 1 addition & 1 deletion .storybook/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const { GlobalStyles } = injectGlobalStyles()

const relayEnvironment = createRelaySSREnvironment({
metaphysicsEndpoint: "https://metaphysics-staging.artsy.net/v2",
cache: JSON.parse(window.__RELAY_BOOTSTRAP__ || "{}"),
cache: JSON.parse(window.__RELAY_HYDRATION_DATA__ || "{}"),
})

export const decorators = [
Expand Down
6 changes: 3 additions & 3 deletions src/System/Relay/__tests__/createRelaySSREnvironment.jest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { QueryResponseCache } from "relay-runtime"
import { hydrateCacheFromSSR } from "../createRelaySSREnvironment"
import { hydrateCacheFromSSR } from "System/Relay/createRelaySSREnvironment"

describe("#hydrateCacheFromSSR", () => {
const relayResponseCache = (new QueryResponseCache({
Expand All @@ -8,7 +8,7 @@ describe("#hydrateCacheFromSSR", () => {
}) as any) as { _responses: Map<any, any> }

it("does not update cache if no ssr data", () => {
window.__RELAY_BOOTSTRAP__
window.__RELAY_HYDRATION_DATA__
hydrateCacheFromSSR(relayResponseCache)
expect(relayResponseCache._responses.size).toBe(0)
})
Expand All @@ -24,7 +24,7 @@ describe("#hydrateCacheFromSSR", () => {
{ id: 1 },
],
]
window.__RELAY_BOOTSTRAP__ = JSON.stringify(request)
window.__RELAY_HYDRATION_DATA__ = JSON.stringify(request)
hydrateCacheFromSSR(relayResponseCache)
expect(relayResponseCache._responses.size).toBe(2)
expect(relayResponseCache._responses.get(request[0][0]).payload.id).toBe(0)
Expand Down
2 changes: 1 addition & 1 deletion src/System/Relay/createRelaySSREnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export function createRelaySSREnvironment(config: Config = {}) {
* @param cache RelayQueryResponseCache
*/
export function hydrateCacheFromSSR(queryResponseCache) {
const ssrData = JSON.parse(window.__RELAY_BOOTSTRAP__ || "{}")
const ssrData = JSON.parse(window.__RELAY_HYDRATION_DATA__ || "{}")

if (!isEmpty(ssrData)) {
try {
Expand Down
64 changes: 5 additions & 59 deletions src/System/Router/Utils/collectAssets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@ import { getENV } from "Utils/getENV"
import { Environment } from "react-relay"
import path from "path"
import { ChunkExtractor } from "@loadable/server"
import serialize from "serialize-javascript"
import { ServerStyleSheet } from "styled-components"
import { renderToString } from "react-dom/server"
import RelayServerSSR, {
SSRCache,
} from "react-relay-network-modern-ssr/lib/server"
import { RelayNetworkLayerResponse } from "react-relay-network-modern"
import RelayServerSSR from "react-relay-network-modern-ssr/lib/server"
import { ENABLE_SSR_STREAMING } from "Server/config"
import { renderToStream } from "System/Router/Utils/renderToStream"
import { ArtsyResponse } from "Server/middleware/artsyExpress"
import { serializeRelayHydrationData } from "System/Router/Utils/serializeRelayHydrationData"

const STATS = "loadable-stats.json"

Expand Down Expand Up @@ -73,10 +70,6 @@ export const collectAssets = async ({

const initialRelayData = await relaySSRMiddleware.getCache()

/**
* Extract scripts from loadable components
* NOTE: When streaming is enabled we need to lazily execute script extraction
*/
const extractScriptTags = () => {
const initialScripts: string[] = []

Expand All @@ -100,33 +93,14 @@ export const collectAssets = async ({
return script
}
})
.filter(script => {
return !(
/**
* Since these files are already embedded in our main
* layout file, omit them from the scripts array.
*
* TODO: Don't include these files in the main layout
* and instead relay on dynamically including them here.
* Will require some shuffling in the jade template,
* however.
*/
(
script.includes("/assets/runtime.") ||
script.includes("/assets/artsy.") ||
script.includes("/assets/common-artsy.") ||
script.includes("/assets/common-react.") ||
script.includes("/assets/common-utility.") ||
script.includes("/assets/common.")
)
)
})
.join("\n")
)

initialScripts.push(`
<script>
var __RELAY_BOOTSTRAP__ = ${serializeRelayData(initialRelayData)};
var __RELAY_HYDRATION_DATA__ = ${serializeRelayHydrationData(
initialRelayData
)};
</script>
`)

Expand All @@ -142,31 +116,3 @@ export const collectAssets = async ({
styleTags,
}
}

const serializeRelayData = (initialRelayData: SSRCache) => {
initialRelayData.forEach(entry => {
entry.forEach((item: RelayNetworkLayerResponse) => {
// Clean relay data of problematic data structures
delete item._res
})
})

let hydrationData

try {
hydrationData = serialize(initialRelayData, {
isJSON: true,
})
} catch (error) {
hydrationData = "{}"

console.error(
"[system/router/collectAssets] Error serializing data:",
error
)
}

return serialize(hydrationData || {}, {
isJSON: true,
})
}
31 changes: 31 additions & 0 deletions src/System/Router/Utils/serializeRelayHydrationData.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { RelayNetworkLayerResponse } from "react-relay-network-modern"
import { SSRCache } from "react-relay-network-modern-ssr/lib/server"
import serialize from "serialize-javascript"

export const serializeRelayHydrationData = (initialRelayData: SSRCache) => {
initialRelayData.forEach(entry => {
entry.forEach((item: RelayNetworkLayerResponse) => {
// Clean relay data of problematic data structures
delete item._res
})
})

let hydrationData

try {
hydrationData = serialize(initialRelayData, {
isJSON: true,
})
} catch (error) {
hydrationData = "{}"

console.error(
"[system/router/serializeRelayHydrationData] Error serializing data:",
error
)
}

return serialize(hydrationData || {}, {
isJSON: true,
})
}
4 changes: 2 additions & 2 deletions src/System/Router/__tests__/clientRouter.jest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe("clientRouter", () => {
})
})

it("bootstraps data from __RELAY_BOOTSTRAP__", async () => {
it("bootstraps data from __RELAY_HYDRATION_DATA__", async () => {
const createRelayEnvSpy = jest.spyOn(
relaySystem,
"createRelaySSREnvironment"
Expand All @@ -82,7 +82,7 @@ describe("clientRouter", () => {
"found window cache",
],
]
window.__RELAY_BOOTSTRAP__ = JSON.stringify(relayBootstrap)
window.__RELAY_HYDRATION_DATA__ = JSON.stringify(relayBootstrap)

const { ClientRouter } = await setupClientRouter({
history: {
Expand Down
2 changes: 1 addition & 1 deletion src/System/Router/__tests__/serverRouter.jest.enzyme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ describe("serverRouter", () => {

it("bootstraps relay SSR data", async () => {
const { extractScriptTags } = await getWrapper()
expect(extractScriptTags?.()).toContain("__RELAY_BOOTSTRAP__")
expect(extractScriptTags?.()).toContain("__RELAY_HYDRATION_DATA__")
})

it("does not prefix CDN_URL if not available", async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/System/Router/clientRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const setupClientRouter = async (
const user = getUser(matchContext.user)

const relayEnvironment = createRelaySSREnvironment({
cache: JSON.parse(window.__RELAY_BOOTSTRAP__ || "{}"),
cache: JSON.parse(window.__RELAY_HYDRATION_DATA__ || "{}"),
user,
})

Expand Down
2 changes: 1 addition & 1 deletion src/Typings/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ declare global {
}
__BOOTSTRAP__?: any
__googleMapsCallback?: () => void
__RELAY_BOOTSTRAP__: string
__RELAY_HYDRATION_DATA__: string
_sift: any
analytics: any
braze?: typeof Braze
Expand Down

0 comments on commit ed0585c

Please sign in to comment.