|
| 1 | +import { getActionContext } from "astro:actions"; |
| 2 | +import { type MiddlewareHandler } from "astro"; |
| 3 | + |
| 4 | +export const onRequest: MiddlewareHandler = async (context, next) => { |
| 5 | + const { action, setActionResult, serializeActionResult } = |
| 6 | + getActionContext(context); |
| 7 | + |
| 8 | + const latestAction = await context.session?.get( |
| 9 | + `smooth-actions:latest-astro-action` |
| 10 | + ); |
| 11 | + |
| 12 | + if (latestAction) { |
| 13 | + // There was an action result stored in the session, so we can restore it |
| 14 | + // for this request and then delete the session entry. This makes it look |
| 15 | + // like the action was executed on this request, and there was no magic |
| 16 | + // redirect happening behind the scenes. |
| 17 | + setActionResult(latestAction.name, latestAction.result); |
| 18 | + await context.session?.delete(`smooth-actions:latest-astro-action`); |
| 19 | + return next(); |
| 20 | + } |
| 21 | + |
| 22 | + if (action?.calledFrom !== "form") { |
| 23 | + // If the action was not called from a form, we can just move on to the next |
| 24 | + // middleware. This is not this middleware's job to handle. |
| 25 | + return next(); |
| 26 | + } |
| 27 | + |
| 28 | + // If we're here, there was an action called from a form, so we need to execute it. Then we |
| 29 | + // store the result in the session so that it can be restored for the next |
| 30 | + // request. |
| 31 | + const result = await action.handler(); |
| 32 | + context.session?.set(`smooth-actions:latest-astro-action`, { |
| 33 | + name: action.name, |
| 34 | + result: serializeActionResult(result), |
| 35 | + }); |
| 36 | + |
| 37 | + if (result.error) { |
| 38 | + // If the action failed, we need to redirect back to the page where the |
| 39 | + // form is located. This is because the form will need to be resubmitted |
| 40 | + // with the error message. |
| 41 | + const referer = context.request.headers.get("Referer"); |
| 42 | + if (!referer) { |
| 43 | + throw new Error("Action submission went wrong"); |
| 44 | + } |
| 45 | + return context.redirect(referer); |
| 46 | + } |
| 47 | + |
| 48 | + // If the action succeeded, we can redirect to the original page. This will |
| 49 | + // get rid of the POST request and replace it with a GET request. |
| 50 | + return context.redirect(context.originPathname); |
| 51 | +}; |
0 commit comments