Skip to content

Commit

Permalink
refactor: clean up some logic
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Oct 21, 2024
1 parent ea4687b commit f8519cc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
12 changes: 4 additions & 8 deletions packages/next-safe-action/src/action-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type {
ServerCodeFn,
StateServerCodeFn,
} from "./index.types";
import { DEFAULT_SERVER_ERROR_MESSAGE, isError } from "./utils";
import { DEFAULT_SERVER_ERROR_MESSAGE, isError, winningBoolean } from "./utils";
import type { MaybePromise } from "./utils.types";
import {
ActionMetadataValidationError,
Expand Down Expand Up @@ -327,13 +327,9 @@ export function actionBuilder<
const actionResult: SafeActionResult<ServerError, IS, BAS, CVE, CBAVE, Data> = {};

if (typeof middlewareResult.validationErrors !== "undefined") {
// Throw validation errors if either `throwValidationErrors` property at the action or instance level is `true`.
// If `throwValidationErrors` property at the action is `false`, do not throw validation errors, since it
// has a higher priority than the instance one.
if (
(utils?.throwValidationErrors || args.throwValidationErrors) &&
utils?.throwValidationErrors !== false
) {
// `utils.throwValidationErrors` has higher priority since it's set at the action level.
// It overrides the client setting, if set.
if (winningBoolean(args.throwValidationErrors, utils?.throwValidationErrors)) {
throw new ActionValidationError(middlewareResult.validationErrors as CVE);
} else {
actionResult.validationErrors = middlewareResult.validationErrors as CVE;
Expand Down
11 changes: 11 additions & 0 deletions packages/next-safe-action/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
export const DEFAULT_SERVER_ERROR_MESSAGE = "Something went wrong while executing the operation.";

/**
* Checks if passed argument is an instance of Error.
*/
export const isError = (error: unknown): error is Error => error instanceof Error;

/**
* Checks what the winning boolean value is from a series of values, from lowest to highest priority.
* `null` and `undefined` values are skipped.
*/
export const winningBoolean = (...args: (boolean | undefined | null)[]) => {
return args.reduce((acc, v) => (typeof v === "boolean" ? v : acc), false) as boolean;
};

0 comments on commit f8519cc

Please sign in to comment.