Skip to content

Commit

Permalink
Rename Request/Response classes to HydrogenRequest and `HydrogenRes…
Browse files Browse the repository at this point in the history
…ponse` (#1408)

* Rename `ServerComponentRequest` to `HydrogenRequest`

* Move `HydrogenRequest` out of weird Hydration folder

* Move test, too

* Rename `ServerComponentResponse` to `HydrogenResponse`

* Update old references of names

* Fix broken references
  • Loading branch information
jplhomer authored Jun 2, 2022
1 parent e213aa8 commit 20ae9c9
Show file tree
Hide file tree
Showing 21 changed files with 119 additions and 142 deletions.
2 changes: 1 addition & 1 deletion docs/framework/hydrogen-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ For advanced use cases, you can provide a function that returns the same propert
let myShopifyConfigCache = {};

export default defineConfig({
shopify: (request: ServerComponentRequest) => {
shopify: (request: HydrogenRequest) => {
// For example, you can change the configuration based on the normalized URL
const url = new URL(request.normalizedUrl);
const [firstUrlPart] = url.pathname.split('/');
Expand Down
12 changes: 6 additions & 6 deletions docs/framework/routes.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,20 +242,20 @@ Server components placed in the `src/routes` directory receive the following spe

| Prop | Type |
| ---------- | ------------------------- |
| `request` | `ServerComponentRequest` |
| `response` | `ServerComponentResponse` |
| `request` | `HydrogenRequest` |
| `response` | `HydrogenResponse` |

Each server component receives props, which includes custom versions of `request` and `response` and any `serverProps` that you have passed from the client.

![Shows a diagram that illustrates how server components receive props](/assets/custom-storefronts/hydrogen/hydrogen-pages.png)

### `request`: `ServerComponentRequest`
### `request`: `HydrogenRequest`

You might want to inspect incoming requests for cookies, headers or other signals that might require a unique response.

All server components receive a `request` prop containing a Hydrogen-specific version of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request).

In addition to the standard methods, `ServerComponentRequest` exposes a `cookies` helper, which is a simple `Map` of cookie values:
In addition to the standard methods, `HydrogenRequest` exposes a `cookies` helper, which is a simple `Map` of cookie values:

{% codeblock file %}

Expand All @@ -273,7 +273,7 @@ function MyPage({request}) {

{% endcodeblock %}

In some cases, you might want to use `ServerComponentRequest.normalizedUrl` to access the intended URL rather than the pathname encoded for a [React Server Components request](https://shopify.dev/custom-storefronts/hydrogen/framework/react-server-components):
In some cases, you might want to use `HydrogenRequest.normalizedUrl` to access the intended URL rather than the pathname encoded for a [React Server Components request](https://shopify.dev/custom-storefronts/hydrogen/framework/react-server-components):

{% codeblock file %}

Expand All @@ -291,7 +291,7 @@ function MyPage({request}) {

{% endcodeblock %}

### `response`: `ServerComponentResponse`
### `response`: `HydrogenResponse`

You might want to customize the response returned from the Hydrogen server. For example, set a different status code or define custom headers.

Expand Down
20 changes: 10 additions & 10 deletions packages/hydrogen/src/entry-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ import type {
ResolvedHydrogenRoutes,
} from './types';
import {Html, applyHtmlHead} from './framework/Hydration/Html';
import {ServerComponentResponse} from './framework/Hydration/ServerComponentResponse.server';
import {HydrogenResponse} from './framework/HydrogenResponse.server';
import {
HydrogenRequest,
RuntimeContext,
ServerComponentRequest,
} from './framework/Hydration/ServerComponentRequest.server';
} from './framework/HydrogenRequest.server';
import {
preloadRequestCacheData,
ServerRequestProvider,
Expand Down Expand Up @@ -91,7 +91,7 @@ export const renderHydrogen = (App: any) => {
streamableResponse: nodeResponse,
} = options;

const request = new ServerComponentRequest(rawRequest);
const request = new HydrogenRequest(rawRequest);
const url = new URL(request.url);

const {default: inlineHydrogenConfig} = await import(
Expand All @@ -117,7 +117,7 @@ export const renderHydrogen = (App: any) => {
setLogger(hydrogenConfig.logger);
const log = getLoggerWithContext(request);

const response = new ServerComponentResponse();
const response = new HydrogenResponse();
const sessionApi = hydrogenConfig.session
? hydrogenConfig.session(log)
: undefined;
Expand Down Expand Up @@ -578,7 +578,7 @@ function PreloadQueries({
request,
children,
}: {
request: ServerComponentRequest;
request: HydrogenRequest;
children: React.ReactNode;
}) {
const preloadQueries = request.getPreloadQueries();
Expand Down Expand Up @@ -611,7 +611,7 @@ type ResponseOptions = {
};

function getResponseOptions(
{headers, status, customStatus}: ServerComponentResponse,
{headers, status, customStatus}: HydrogenResponse,
error?: Error
) {
const responseInit = {} as ResponseOptions;
Expand All @@ -633,7 +633,7 @@ function getResponseOptions(

function writeHeadToNodeResponse(
nodeResponse: ServerResponse,
componentResponse: ServerComponentResponse,
componentResponse: HydrogenResponse,
log: Logger,
error?: Error
) {
Expand Down Expand Up @@ -682,8 +682,8 @@ function flightContainer(chunk: string) {
function postRequestTasks(
type: RenderType,
status: number,
request: ServerComponentRequest,
response: ServerComponentResponse
request: HydrogenRequest,
response: HydrogenResponse
) {
logServerResponse(type, request, status);
logCacheControlHeaders(type, request, response);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, {Suspense} from 'react';
import {ServerComponentRequest} from '../../../framework/Hydration/ServerComponentRequest.server';
import {HydrogenRequest} from '../../../framework/HydrogenRequest.server';
import {mountWithProviders} from '../../../utilities/tests/shopifyMount';
import {ServerRequestProvider} from '../../ServerRequestProvider';
import {Analytics} from '../Analytics.server';
Expand All @@ -15,7 +15,7 @@ function SomeApiDelayServerComponent({
request,
}: {
delay: number;
request: ServerComponentRequest;
request: HydrogenRequest;
}) {
const cache = request.ctx.cache;
const delayKey = `api-${delay}`;
Expand Down Expand Up @@ -44,10 +44,7 @@ function SomeApiDelayServerComponent({
return <div>Api delay - {delay}</div>;
}

function mountComponent(
request: ServerComponentRequest,
children: React.ReactChild
) {
function mountComponent(request: HydrogenRequest, children: React.ReactChild) {
return mountWithProviders(
<ServerRequestProvider request={request} isRSC={true}>
<Suspense fallback={null}>
Expand All @@ -62,9 +59,7 @@ function mountComponent(

describe('Analytics.server', () => {
it('should introduce delay if no cache queries are detected', async () => {
const request = new ServerComponentRequest(
new Request('https://examples.com')
);
const request = new HydrogenRequest(new Request('https://examples.com'));
const analyticsData = {
test: '123',
};
Expand All @@ -88,9 +83,7 @@ describe('Analytics.server', () => {
});

it('should wait for all cache queries', async () => {
const request = new ServerComponentRequest(
new Request('https://examples.com')
);
const request = new HydrogenRequest(new Request('https://examples.com'));
await mountComponent(
request,
<>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, {Suspense} from 'react';
import {ServerComponentRequest} from '../../../framework/Hydration/ServerComponentRequest.server';
import {HydrogenRequest} from '../../../framework/HydrogenRequest.server';
import {mountWithProviders} from '../../../utilities/tests/shopifyMount';
import {ServerRequestProvider} from '../../ServerRequestProvider';
import {useServerAnalytics} from '../hook';
Expand All @@ -10,9 +10,7 @@ function mountComponent(analyticsData?: any) {
return <div>{JSON.stringify(result)}</div>;
}

const request = new ServerComponentRequest(
new Request('https://examples.com')
);
const request = new HydrogenRequest(new Request('https://examples.com'));

return mountWithProviders(
<ServerRequestProvider request={request} isRSC={true}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import {getTime} from '../../utilities/timing';
import {hashKey} from '../../utilities/hash';
import type {
PreloadQueriesByURL,
ServerComponentRequest,
} from '../../framework/Hydration/ServerComponentRequest.server';
HydrogenRequest,
} from '../../framework/HydrogenRequest.server';
import type {QueryKey} from '../../types';
import {collectQueryTimings} from '../../utilities/log';

// Context to inject current request in SSR
const RequestContextSSR = createContext<ServerComponentRequest | null>(null);
const RequestContextSSR = createContext<HydrogenRequest | null>(null);

// Cache to inject current request in RSC
function requestCacheRSC() {
Expand All @@ -20,7 +20,7 @@ requestCacheRSC.key = Symbol.for('HYDROGEN_REQUEST');

type ServerRequestProviderProps = {
isRSC: boolean;
request: ServerComponentRequest;
request: HydrogenRequest;
children: JSX.Element;
};

Expand Down Expand Up @@ -68,7 +68,7 @@ export function ServerRequestProvider({
}

export function useServerRequest() {
let request: ServerComponentRequest | null;
let request: HydrogenRequest | null;
try {
// This cache only works during RSC rendering:
// @ts-ignore
Expand All @@ -85,7 +85,7 @@ export function useServerRequest() {
if (__HYDROGEN_TEST__) {
// Unit tests are not wrapped in ServerRequestProvider.
// This mocks it, instead of providing it in every test.
return {ctx: {}} as ServerComponentRequest;
return {ctx: {}} as HydrogenRequest;
}

throw new Error('No ServerRequest Context found');
Expand Down Expand Up @@ -156,7 +156,7 @@ export function useRequestCacheData<T>(
}

export function preloadRequestCacheData(
request: ServerComponentRequest,
request: HydrogenRequest,
preloadQueries?: PreloadQueriesByURL
): void {
const cache = request.ctx.cache;
Expand Down
8 changes: 4 additions & 4 deletions packages/hydrogen/src/foundation/session/session.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Logger} from '../../utilities/log';
import {wrapPromise} from '../../utilities/suspense';
import type {ServerComponentResponse} from '../../framework/Hydration/ServerComponentResponse.server';
import type {ServerComponentRequest} from '../../framework/Hydration/ServerComponentRequest.server';
import type {HydrogenResponse} from '../../framework/HydrogenResponse.server';
import type {HydrogenRequest} from '../../framework/HydrogenRequest.server';

export type SessionSyncApi = {
get: () => Record<string, string>;
Expand All @@ -20,8 +20,8 @@ export type SessionStorageAdapter = {
};

export function getSyncSessionApi(
request: ServerComponentRequest,
componentResponse: ServerComponentResponse,
request: HydrogenRequest,
componentResponse: HydrogenResponse,
log: Logger,
session?: SessionStorageAdapter
) {
Expand Down
4 changes: 2 additions & 2 deletions packages/hydrogen/src/foundation/ssr-interop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
*/

import {useContext, Context} from 'react';
import type {ServerComponentRequest} from '../framework/Hydration/ServerComponentRequest.server';
import type {HydrogenRequest} from '../framework/HydrogenRequest.server';
//@SSR import {useServerRequest} from './ServerRequestProvider';

// This is replaced by Vite to import.meta.env.SSR
export const META_ENV_SSR = false;

type ServerGetter<T> = (request: ServerComponentRequest) => T;
type ServerGetter<T> = (request: HydrogenRequest) => T;

const reactContextType = Symbol.for('react.context');

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import type {ShopifyContextValue} from '../../foundation/ShopifyProvider/types';
import {getTime} from '../../utilities/timing';
import type {QueryCacheControlHeaders} from '../../utilities/log/log-cache-header';
import type {QueryTiming} from '../../utilities/log/log-query-timeline';
import type {
ResolvedHydrogenConfig,
PreloadOptions,
QueryKey,
} from '../../types';
import {hashKey} from '../../utilities/hash';
import type {ShopifyContextValue} from '../foundation/ShopifyProvider/types';
import {getTime} from '../utilities/timing';
import type {QueryCacheControlHeaders} from '../utilities/log/log-cache-header';
import type {QueryTiming} from '../utilities/log/log-query-timeline';
import type {ResolvedHydrogenConfig, PreloadOptions, QueryKey} from '../types';
import {hashKey} from '../utilities/hash';
import {HelmetData as HeadData} from 'react-helmet-async';
import {RSC_PATHNAME} from '../../constants';
import {SessionSyncApi} from '../../foundation/session/session';
import {parseJSON} from '../../utilities/parse';
import {RSC_PATHNAME} from '../constants';
import {SessionSyncApi} from '../foundation/session/session';
import {parseJSON} from '../utilities/parse';

export interface RuntimeContext {
waitUntil: (fn: Promise<any>) => void;
Expand Down Expand Up @@ -50,7 +46,7 @@ const PRELOAD_ALL = '*';
* - Adds a `cookies` map for easy access
* - Adds a static constructor to convert a Node.js `IncomingMessage` to a Request.
*/
export class ServerComponentRequest extends Request {
export class HydrogenRequest extends Request {
public cookies: Map<string, string>;
public id: string;
public time: number;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {CacheSeconds, generateCacheControlHeader} from '../CachingStrategy';
import type {CachingStrategy} from '../../types';
import Redirect from '../../foundation/Redirect/Redirect.client';
import {CacheSeconds, generateCacheControlHeader} from './CachingStrategy';
import type {CachingStrategy} from '../types';
import Redirect from '../foundation/Redirect/Redirect.client';
import React from 'react';

export class ServerComponentResponse extends Response {
export class HydrogenResponse extends Response {
private wait = false;
private cacheOptions: CachingStrategy = CacheSeconds();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export default (pluginOptions: HydrogenVitePluginOptions) => {
});

// @ts-expect-error Manually set `normalizedUrl` which a developer expects to be available
// via `ServerComponentRequest` during production runtime.
// via `HydrogenRequest` during production runtime.
request.normalizedUrl = request.url;

const {shopify} = hydrogenConfig;
Expand Down
Loading

0 comments on commit 20ae9c9

Please sign in to comment.