diff options
Diffstat (limited to 'packages/astro/templates/actions.mjs')
-rw-r--r-- | packages/astro/templates/actions.mjs | 54 |
1 files changed, 24 insertions, 30 deletions
diff --git a/packages/astro/templates/actions.mjs b/packages/astro/templates/actions.mjs index 1101c1361..fbd89d75d 100644 --- a/packages/astro/templates/actions.mjs +++ b/packages/astro/templates/actions.mjs @@ -7,36 +7,30 @@ function toActionProxy(actionCallback = {}, aggregatedPath = '') { return target[objKey]; } const path = aggregatedPath + objKey.toString(); - const action = (param) => actionHandler(param, path); + const action = (param) => callSafely(() => handleActionOrThrow(param, path)); - action.toString = () => getActionQueryString(path); - action.queryString = action.toString(); - action.safe = (input) => { - return callSafely(() => action(input)); - }; - action.safe.toString = () => action.toString(); + Object.assign(action, { + queryString: getActionQueryString(path), + toString: () => action.queryString, + // Progressive enhancement info for React. + $$FORM_ACTION: function () { + return { + method: 'POST', + // `name` creates a hidden input. + // It's unused by Astro, but we can't turn this off. + // At least use a name that won't conflict with a user's formData. + name: '_astroAction', + action: action.toString(), + }; + }, + // Note: `orThrow` does not have progressive enhancement info. + // If you want to throw exceptions, + // you must handle those exceptions with client JS. + orThrow: (param) => { + return handleActionOrThrow(param, path); + }, + }); - // Add progressive enhancement info for React. - action.$$FORM_ACTION = function () { - return { - method: 'POST', - // `name` creates a hidden input. - // It's unused by Astro, but we can't turn this off. - // At least use a name that won't conflict with a user's formData. - name: '_astroAction', - action: action.toString(), - }; - }; - action.safe.$$FORM_ACTION = function () { - const data = new FormData(); - data.set('_astroActionSafe', 'true'); - return { - method: 'POST', - name: '_astroAction', - action: action.toString(), - data, - }; - }; // recurse to construct queries for nested object paths // ex. actions.user.admins.auth() return toActionProxy(action, path + '.'); @@ -49,14 +43,14 @@ function toActionProxy(actionCallback = {}, aggregatedPath = '') { * @param {string} path Built path to call action by path name. * Usage: `actions.[name](param)`. */ -async function actionHandler(param, path) { +async function handleActionOrThrow(param, path) { // When running server-side, import the action and call it. if (import.meta.env.SSR) { const { getAction } = await import('astro/actions/runtime/utils.js'); const action = await getAction(path); if (!action) throw new Error(`Action not found: ${path}`); - return action(param); + return action.orThrow(param); } // When running client-side, make a fetch request to the action path. |