0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

feat: success property

This commit is contained in:
bholmesdev 2024-08-21 16:47:34 -04:00
parent 735767f8df
commit 77e9fd0217
3 changed files with 11 additions and 6 deletions

View file

@ -113,10 +113,12 @@ export function isInputError<T extends ErrorInferenceObject>(
export type SafeResult<TInput extends ErrorInferenceObject, TOutput> =
| {
success: true;
data: TOutput;
error: undefined;
}
| {
success: false;
data: undefined;
error: ActionError<TInput>;
};
@ -153,12 +155,13 @@ export async function callSafely<TOutput>(
): Promise<SafeResult<z.ZodType, TOutput>> {
try {
const data = await handler();
return { data, error: undefined };
return { success: true, data, error: undefined };
} catch (e) {
if (e instanceof ActionError) {
return { data: undefined, error: e };
return { success: false, data: undefined, error: e };
}
return {
success: false,
data: undefined,
error: new ActionError({
message: e instanceof Error ? e.message : 'Unknown error',
@ -246,20 +249,22 @@ export function serializeActionResult(res: SafeResult<any, any>): SerializedActi
export function deserializeActionResult(res: SerializedActionResult): SafeResult<any, any> {
if (res.type === 'error') {
if (import.meta.env?.PROD) {
return { error: ActionError.fromJson(JSON.parse(res.body)), data: undefined };
return { success: false, error: ActionError.fromJson(JSON.parse(res.body)), data: undefined };
} else {
const error = ActionError.fromJson(JSON.parse(res.body));
error.stack = actionResultErrorStack.get();
return {
success: false,
error,
data: undefined,
};
}
}
if (res.type === 'empty') {
return { data: undefined, error: undefined };
return { success: true, data: undefined, error: undefined };
}
return {
success: true,
data: devalueParse(res.body, {
URL: (href) => new URL(href),
}),

View file

@ -3,7 +3,7 @@ import { actions } from 'astro:actions';
const res = Astro.getActionResult(actions.getUserOrThrow);
if (res?.error) {
if (res?.success === false) {
Astro.response.status = res.error.status;
}
---

View file

@ -4,4 +4,4 @@ import { actions } from 'astro:actions';
const res = Astro.getActionResult(actions.getUser);
---
<h1 id="user">{res?.data?.name}</h1>
<h1 id="user">{res?.success ? res.data.name : 'Failed'}</h1>