Skip to content

Commit

Permalink
feat(middleware): support standalone middleware definition via export…
Browse files Browse the repository at this point in the history
…ed `createMiddleware` function
  • Loading branch information
TheEdoRan committed Aug 12, 2024
1 parent cfc1b8c commit 87868a2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/next-safe-action/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
formatValidationErrors,
} from "./validation-errors";

export { ActionMetadataError, DEFAULT_SERVER_ERROR_MESSAGE } from "./utils";
export { ActionMetadataError, createMiddleware, DEFAULT_SERVER_ERROR_MESSAGE } from "./utils";
export {
ActionValidationError,
flattenBindArgsValidationErrors,
Expand Down
22 changes: 22 additions & 0 deletions packages/next-safe-action/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { MiddlewareFn } from "./index.types";

export const DEFAULT_SERVER_ERROR_MESSAGE = "Something went wrong while executing the operation.";

export const isError = (error: unknown): error is Error => error instanceof Error;
Expand Down Expand Up @@ -28,3 +30,23 @@ export class ActionMetadataError extends Error {
this.name = "ActionMetadataError";
}
}

/**
* Creates a standalone middleware function. It accepts a generic object with optional `serverError`, `ctx` and `metadata`
* properties, if you need one or all of them to be typed. The type for each property that is passed as generic is the
* **minimum** shape required to define the middleware function, but it can also be larger than that.
*
* {@link https://next-safe-action.dev/docs/safe-action-client/middleware#create-standalone-middleware-with-createmiddleware See docs for more information}
*/
export const createMiddleware = <BaseData extends { serverError?: any; ctx?: object; metadata?: any }>() => {
return {
define: <NextCtx extends object>(
middlewareFn: MiddlewareFn<
BaseData extends { serverError: infer SE } ? SE : any,
BaseData extends { metadata: infer MD } ? MD : any,
BaseData extends { ctx: infer Ctx extends object } ? Ctx : object,
NextCtx
>
) => middlewareFn,
};
};

0 comments on commit 87868a2

Please sign in to comment.