Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react-server): add ActionContext.revalidate #268

Merged
merged 3 commits into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/react-server/examples/basic/e2e/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,27 @@ async function testActionContext(page: Page) {
await page.getByText("Hi, anonymous user!").click();
}

test("action revalidate", async ({ page }) => {
checkNoError(page);

await page.goto("/test/action");
await waitForHydration(page);

const checkClientState = await setupCheckClientState(page);

if (process.env.E2E_PREVIEW) {
await page.getByText("[effect: 1]").click();
await page.getByRole("button", { name: "Revalidate!" }).click();
await page.getByText("[effect: 2]").click();
} else {
await page.getByText("[effect: 2]").click();
await page.getByRole("button", { name: "Revalidate!" }).click();
await page.getByText("[effect: 3]").click();
}

await checkClientState();
});

test("dynamic routes", async ({ page }) => {
checkNoError(page);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use server";

import type { ActionContext } from "@hiogawa/react-server/server";
import { sleep, tinyassert } from "@hiogawa/utils";

let counter = 0;
Expand Down Expand Up @@ -35,3 +36,7 @@ export async function actionCheckAnswer(formData: FormData) {
const message = answer === 2 ? "Correct!" : "Wrong!";
return { message };
}

export async function actionTestRevalidate(this: ActionContext) {
this.revalidate = true;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { changeCounter, getCounter, getMessages } from "./_action";
import {
actionTestRevalidate,
changeCounter,
getCounter,
getMessages,
} from "./_action";
import {
ActionDataTest,
Chat,
Expand All @@ -17,6 +22,10 @@ export default async function Page() {
</div>
<Chat messages={getMessages()} />
<ActionDataTest />
<form action={actionTestRevalidate} className="flex flex-col gap-2">
<h4 className="font-bold">Action Revalidate</h4>
<button className="antd-btn antd-btn-default w-sm">Revalidate!</button>
</form>
<FormStateTest />
</div>
);
Expand Down
29 changes: 22 additions & 7 deletions packages/react-server/src/entry/react-server.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { createDebug, objectMapKeys, objectMapValues } from "@hiogawa/utils";
import {
createDebug,
objectMapKeys,
objectMapValues,
objectPick,
} from "@hiogawa/utils";
import type { RenderToReadableStreamOptions } from "react-dom/server";
import reactServerDomServer from "react-server-dom-webpack/server.edge";
import {
type ActionResult,
type LayoutRequest,
type ServerRouterData,
} from "../features/router/utils";
import { type ActionContext } from "../features/server-action/react-server";
import {
ActionContext,
type ActionResult,
} from "../features/server-action/react-server";
import { ejectActionId } from "../features/server-action/utils";
import { unwrapStreamRequest } from "../features/server-component/utils";
import { createBundlerConfig } from "../features/use-client/react-server";
Expand Down Expand Up @@ -47,7 +54,10 @@ export const handler: ReactServerHandler = async (ctx) => {
}

// check stream only request
const { request, layoutRequest, isStream } = unwrapStreamRequest(ctx.request);
const { request, layoutRequest, isStream } = unwrapStreamRequest(
ctx.request,
actionResult,
);
const stream = await render({ request, layoutRequest, actionResult });

if (isStream) {
Expand Down Expand Up @@ -82,7 +92,12 @@ async function render({
);
const bundlerConfig = createBundlerConfig();
return reactServerDomServer.renderToReadableStream<ServerRouterData>(
{ layout: nodeMap, action: actionResult },
{
layout: nodeMap,
action: actionResult
? objectPick(actionResult, ["id", "data", "error"])
: undefined,
},
bundlerConfig,
{
onError: reactServerOnError,
Expand Down Expand Up @@ -150,8 +165,8 @@ async function actionHandler({ request }: { request: Request }) {
action = mod[name];
}

const context: ActionContext = { request, responseHeaders: {} };
const result: ActionResult = { id };
const context = new ActionContext(request);
const result: ActionResult = { id, context };
try {
result.data = await action.apply(context, [formData]);
} catch (e) {
Expand Down
12 changes: 2 additions & 10 deletions packages/react-server/src/features/router/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ReactServerErrorContext } from "../../server";
import type { ActionResult } from "../server-action/react-server";

export type LayoutRequest = Record<
string,
Expand All @@ -8,16 +8,8 @@ export type LayoutRequest = Record<
}
>;

// TODO: discriminated union
export type ActionResult = {
id?: string;
error?: ReactServerErrorContext;
data?: unknown;
responseHeaders?: Record<string, string>;
};

export type ServerRouterData = {
action?: ActionResult;
action?: Pick<ActionResult, "id" | "error" | "data">;
layout: Record<string, React.ReactNode>;
};

Expand Down
20 changes: 16 additions & 4 deletions packages/react-server/src/features/server-action/react-server.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ReactServerErrorContext } from "../../server";

export function createServerReference(id: string, action: Function): React.FC {
return Object.defineProperties(action, {
$$typeof: {
Expand All @@ -17,8 +19,18 @@ export function createServerReference(id: string, action: Function): React.FC {
}) as any;
}

// action function can access context via (this: ActionContext)
export interface ActionContext {
request: Request;
responseHeaders: Record<string, string>; // TODO: Headers?
// TODO: discriminated union
export type ActionResult = {
id: string;
error?: ReactServerErrorContext;
data?: unknown;
responseHeaders?: Record<string, string>;
context: ActionContext;
};

export class ActionContext {
responseHeaders: Record<string, string> = {};
revalidate = false;

constructor(public request: Request) {}
}
8 changes: 6 additions & 2 deletions packages/react-server/src/features/server-component/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
createLayoutContentRequest,
getNewLayoutContentKeys,
} from "../router/utils";
import type { ActionResult } from "../server-action/react-server";

// TODO: use accept header x-component?
const RSC_PARAM = "__rsc";
Expand All @@ -22,13 +23,16 @@ export function wrapStreamRequestUrl(
return newUrl.toString();
}

export function unwrapStreamRequest(request: Request) {
export function unwrapStreamRequest(
request: Request,
actionResult?: ActionResult,
) {
const url = new URL(request.url);
const rscParam = url.searchParams.get(RSC_PARAM);
url.searchParams.delete(RSC_PARAM);

let layoutRequest = createLayoutContentRequest(url.pathname);
if (rscParam) {
if (rscParam && !actionResult?.context.revalidate) {
const param = JSON.parse(rscParam);
if (param.lastPathname && !param.invalidateAll) {
const newKeys = getNewLayoutContentKeys(param.lastPathname, url.pathname);
Expand Down