Commit d31472c4 authored by Janka Uryga's avatar Janka Uryga

refactor: nicer return types in action handler

parent eb2a8512
......@@ -455,12 +455,19 @@ type HandleActionResult =
type: 'not-found'
}
| {
/** The request turned out to not be an action. */
type: 'not-an-action'
}
| {
/** We decoded a FormState, but haven't rendered anything yet. */
type: 'form-state'
formState: any
}
| {
/** A finished result. */
type: 'done'
result: RenderResult | undefined
formState?: any
result: RenderResult
}
/** The request turned out not to be a server action. */
| null
export async function handleAction({
req,
......@@ -500,7 +507,7 @@ export async function handleAction({
// Note that this can be a false positive -- any multipart/urlencoded POST can get us here,
// But won't know if it's an MPA action or not until we call `decodeAction` below.
if (!isPossibleServerAction) {
return null
return { type: 'not-an-action' }
}
if (workStore.isStaticGeneration) {
......@@ -696,36 +703,35 @@ export async function handleAction({
throwIfActionNotInModuleMap(serverModuleMap)
)
if (typeof action === 'function') {
// an MPA action.
if (typeof action !== 'function') {
// We couldn't decode an action, so this POST request turned out not to be a server action request.
return { type: 'not-an-action' }
}
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
// an MPA action.
const actionReturnedState =
await executeActionAndPrepareForRender(
action as () => Promise<unknown>,
[],
workStore,
requestStore
)
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
const formState = await decodeFormState(
actionReturnedState,
formData,
serverModuleMap
const actionReturnedState =
await executeActionAndPrepareForRender(
action as () => Promise<unknown>,
[],
workStore,
requestStore
)
// Skip the fetch path.
// We need to render a full HTML version of the page for the response, we'll handle that in app-render.
return {
type: 'done',
result: undefined,
formState,
}
} else {
// We couldn't decode an action, so this POST request turned out not to be a server action request.
return null
const formState = await decodeFormState(
actionReturnedState,
formData,
serverModuleMap
)
// Skip the fetch path.
// We need to render a full HTML version of the page for the response, we'll handle that in app-render.
return {
type: 'form-state',
formState,
}
}
} else {
......@@ -734,7 +740,7 @@ export async function handleAction({
// If it's not multipart AND not a fetch action,
// then it can't be an action request.
if (!isFetchAction) {
return null
return { type: 'not-an-action' }
}
try {
......@@ -901,36 +907,35 @@ export async function handleAction({
throwIfActionNotInModuleMap(serverModuleMap)
)
if (typeof action === 'function') {
// an MPA action.
if (typeof action !== 'function') {
// We couldn't decode an action, so this POST request turned out not to be a server action request.
return { type: 'not-an-action' }
}
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
// an MPA action.
const actionReturnedState =
await executeActionAndPrepareForRender(
action as () => Promise<unknown>,
[],
workStore,
requestStore
)
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
const formState = await decodeFormState(
actionReturnedState,
formData,
serverModuleMap
const actionReturnedState =
await executeActionAndPrepareForRender(
action as () => Promise<unknown>,
[],
workStore,
requestStore
)
// Skip the fetch path.
// We need to render a full HTML version of the page for the response, we'll handle that in app-render.
return {
type: 'done',
result: undefined,
formState,
}
} else {
// We couldn't decode an action, so this POST request turned out not to be a server action request.
return null
const formState = await decodeFormState(
actionReturnedState,
formData,
serverModuleMap
)
// Skip the fetch path.
// We need to render a full HTML version of the page for the response, we'll handle that in app-render.
return {
type: 'form-state',
formState,
}
}
} else {
......@@ -939,7 +944,7 @@ export async function handleAction({
// If it's not multipart AND not a fetch action,
// then it can't be an action request.
if (!isFetchAction) {
return null
return { type: 'not-an-action' }
}
try {
......@@ -978,6 +983,11 @@ export async function handleAction({
throw new Error('Invariant: Unknown request type.')
}
// Handle a fetch action.
// Ensure that non-fetch codepaths can't reach this part.
isFetchAction satisfies true
// actions.js
// app/page.js
// action worker1
......@@ -993,6 +1003,7 @@ export async function handleAction({
const actionMod = (await ComponentMod.__next_app__.require(
actionModId
)) as Record<string, (...args: unknown[]) => Promise<unknown>>
const actionHandler = actionMod[actionId]
const returnVal = await executeActionAndPrepareForRender(
......@@ -1004,23 +1015,16 @@ export async function handleAction({
addRevalidationHeader(res, { workStore, requestStore })
})
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
const actionResult = await generateFlight(req, ctx, requestStore, {
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
temporaryReferences,
})
const actionResult = await generateFlight(req, ctx, requestStore, {
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
temporaryReferences,
})
return {
type: 'done',
result: actionResult,
}
} else {
// TODO: this shouldn't be reachable, because all non-fetch codepaths return early.
// this will be handled in a follow-up refactor PR.
return null
return {
type: 'done',
result: actionResult,
}
}
)
......
......@@ -1585,31 +1585,40 @@ async function renderToHTMLOrFlightImpl(
metadata,
})
if (actionRequestResult) {
if (actionRequestResult.type === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
res.statusCode = 404
metadata.statusCode = 404
const stream = await renderToStreamWithTracing(
requestStore,
req,
res,
ctx,
notFoundLoaderTree,
formState,
postponedState,
metadata
)
if (actionRequestResult.type === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
res.statusCode = 404
metadata.statusCode = 404
const stream = await renderToStreamWithTracing(
requestStore,
req,
res,
ctx,
workStore,
notFoundLoaderTree,
formState,
postponedState,
metadata
)
return new RenderResult(stream, { metadata })
} else if (actionRequestResult.type === 'done') {
if (actionRequestResult.result) {
actionRequestResult.result.assignMetadata(metadata)
return actionRequestResult.result
} else if (actionRequestResult.formState) {
formState = actionRequestResult.formState
}
}
return new RenderResult(stream, { metadata })
} else if (actionRequestResult.type === 'done') {
// We ran the action, and have a flight result. Nothing more to do here.
actionRequestResult.result.assignMetadata(metadata)
return actionRequestResult.result
} else if (actionRequestResult.type === 'form-state') {
// an MPA action. We ran the action, but haven't rendered anything yet, only decoded a form state.
// We need to produce an HTML response, so continue rendering below.
formState = actionRequestResult.formState
} else if (actionRequestResult.type === 'not-an-action') {
// This is likely a form submission request targetting a page. Generally, this can happen if:
// - the user did `<form action="/this-page">` using a vanilla HTML form
// - the user did `<form action="/router-handler">` using a vanilla HTML form,
// and the route handler responded with a 307/308 to a page, so the browser retried the POST request at the new URL
// In both of these cases we should render the page to HTML as a response.
//
// TODO: we should consider disallowing these requests altogether, because they only work for dynamic pages,
// and would stop working if the page became static. (a POST to a static page will result in a 405).
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment