mirror of
https://github.com/Sendouc/sendou.ink.git
synced 2026-10-01 23:58:36 -05:00
Move app to apps/web-react in pnpm workspace layout
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import type { ActionFunction, ActionFunctionArgs } from "react-router";
|
||||
|
||||
/**
|
||||
* Wraps an existing action function for API use.
|
||||
* Converts redirect-based success/error responses to JSON responses.
|
||||
*
|
||||
* The existing actions use:
|
||||
* - `successToast(message)` which returns `redirect("?__success=message")`
|
||||
* - `errorToastIfFalsy/errorToastIfErr` which throw `redirect("?__error=message")`
|
||||
* - `{ fieldErrors }` returns for form validation failures
|
||||
*/
|
||||
export async function wrapActionForApi(
|
||||
actionFn: ActionFunction,
|
||||
args: ActionFunctionArgs,
|
||||
): Promise<Response> {
|
||||
try {
|
||||
const response = await actionFn(args);
|
||||
|
||||
if (response instanceof Response && response.status === 302) {
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
|
||||
if (response && typeof response === "object" && "fieldErrors" in response) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "Validation failed",
|
||||
fieldErrors: response.fieldErrors,
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return response as Response;
|
||||
} catch (e) {
|
||||
if (e instanceof Response && e.status === 302) {
|
||||
const location = e.headers.get("Location") ?? "";
|
||||
const search = location.slice(location.indexOf("?") + 1);
|
||||
const errorMsg = new URLSearchParams(search).get("__error");
|
||||
if (errorMsg !== null) {
|
||||
return new Response(JSON.stringify({ error: errorMsg }), {
|
||||
status: 400,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user