Skip to content

Commit

Permalink
refactor: rename define method to action
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Apr 8, 2024
1 parent dbd9639 commit 1617d22
Show file tree
Hide file tree
Showing 18 changed files with 33 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const onboardUser = action
z.string().uuid(),
z.number().min(18).max(150),
])
.define(
.action(
async ({
parsedInput: { username },
bindArgsParsedInputs: [userId, age],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const schema = z.object({
export const loginUser = action
.metadata({ actionName: "loginUser" })
.schema(schema)
.define(async ({ parsedInput: { username, password } }) => {
.action(async ({ parsedInput: { username, password } }) => {
if (username === "johndoe") {
returnValidationErrors(schema, {
username: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const schema = z.object({
export const deleteUser = action
.metadata({ actionName: "deleteUser" })
.schema(schema)
.define(async ({ parsedInput: { userId } }) => {
.action(async ({ parsedInput: { userId } }) => {
await new Promise((res) => setTimeout(res, 1000));

if (Math.random() > 0.5) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const schema = z
export const buyProduct = action
.metadata({ actionName: "buyProduct" })
.schema(schema)
.define(async () => {
.action(async () => {
return {
success: true,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const schema = z.object({
export const addLikes = action
.metadata({ actionName: "addLikes" })
.schema(schema)
.define(async ({ parsedInput: { incrementBy } }) => {
.action(async ({ parsedInput: { incrementBy } }) => {
await new Promise((res) => setTimeout(res, 2000));

const likesCount = incrementLikes(incrementBy);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { schema } from "./validation";
export const buyProduct = action
.metadata({ actionName: "buyProduct" })
.schema(schema)
.define(async ({ parsedInput: { productId } }) => {
.action(async ({ parsedInput: { productId } }) => {
return {
productId,
transactionId: randomUUID(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const schema = zfd.formData({
export const signup = action
.metadata({ actionName: "signup" })
.schema(schema)
.define(async ({ parsedInput: { email, password } }) => {
.action(async ({ parsedInput: { email, password } }) => {
console.log("Email:", email, "Password:", password);
return {
success: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const schema = object({
export const editUser = authAction
.metadata({ actionName: "editUser" })
.schema(schema)
.define(
.action(
// Here you have access to `userId`, and `sessionId which comes from middleware functions
// defined before.
// \\\\\\\\\\\\\\\\\\
Expand Down
10 changes: 5 additions & 5 deletions packages/next-safe-action/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ class SafeActionClient<const ServerError, const Ctx = null> {
* @param serverCodeFn A function that executes the server code.
* @returns {SafeActionFn}
*/
#define<const S extends Schema, const BAS extends Schema[], const Data = null>(
#action<const S extends Schema, const BAS extends Schema[], const Data = null>(
schema: S,
bindArgsSchemas: BAS,
serverCodeFn: ServerCodeFn<S, BAS, Data, Ctx>
Expand Down Expand Up @@ -238,8 +238,8 @@ class SafeActionClient<const ServerError, const Ctx = null> {
bindArgsSchemas: BAS
) {
return {
define: <const Data = null>(serverCodeFn: ServerCodeFn<S, BAS, Data, Ctx>) =>
this.#define(mainSchema, bindArgsSchemas, serverCodeFn),
action: <const Data = null>(serverCodeFn: ServerCodeFn<S, BAS, Data, Ctx>) =>
this.#action(mainSchema, bindArgsSchemas, serverCodeFn),
};
}

Expand All @@ -252,8 +252,8 @@ class SafeActionClient<const ServerError, const Ctx = null> {
return {
bindArgsSchemas: <const BAS extends Schema[]>(bindArgsSchemas: BAS) =>
this.#bindArgsSchemas(schema, bindArgsSchemas),
define: <const Data = null>(serverCodeFn: ServerCodeFn<S, [], Data, Ctx>) =>
this.#define(schema, [], serverCodeFn),
action: <const Data = null>(serverCodeFn: ServerCodeFn<S, [], Data, Ctx>) =>
this.#action(schema, [], serverCodeFn),
};
}
}
Expand Down
8 changes: 4 additions & 4 deletions website/docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ This is a basic client, without any options or middleware functions. If you want

### 2. Define a new action

This is how a safe action is created. Providing a validation input schema to the function via `schema()`, we're sure that data that comes in is type safe and validated.
The `define()` method lets you define what happens on the server when the action is called from client, via an async function that receives the parsed input and context as arguments. In short, this is your _server code_. **It never runs on the client**:
This is how a safe action is created. Providing a validation input schema to the function via [`schema()`](docs/safe-action-client/instance-methods#schema), we're sure that data that comes in is type safe and validated.
The [`action()`](/docs/safe-action-client/instance-methods#action) method lets you define what happens on the server when the action is called from client, via an async function that receives the parsed input and context as arguments. In short, this is your _server code_. **It never runs on the client**:

```typescript title="src/app/login-action.ts"
"use server"; // don't forget to add this!
Expand All @@ -64,7 +64,7 @@ const schema = z.object({

export const loginUser = actionClient
.schema(schema)
.define(async ({ parsedInput: { username, password } }) => {
.action(async ({ parsedInput: { username, password } }) => {
if (username === "johndoe" && password === "123456") {
return {
success: "Successfully logged in",
Expand All @@ -75,7 +75,7 @@ export const loginUser = actionClient
});
```

`action` returns a new function that can be called from the client.
`action` returns a function that can be called from the client.

### 3. Import and execute the action

Expand Down
2 changes: 1 addition & 1 deletion website/docs/integrations/react-hook-form.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { schema } from "./validation";

export const buyProduct = actionClient
.schema(schema)
.define(async ({ parsedInput: { productId } }) => {
.action(async ({ parsedInput: { productId } }) => {
// We're just returning the productId passed to the action here.
return {
productId,
Expand Down
16 changes: 8 additions & 8 deletions website/docs/safe-action-client/instance-methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,31 +29,31 @@ use<const ClientInput, const NextCtx>(middlewareFn: MiddlewareFn<ClientInput, Ct
metadata(data: ActionMetadata) => { schema() }
```

`metadata` expects an object of type [`ActionMetadata`](/docs/types#actionmetadata) that lets you specify useful data about the safe action you're defining, and it returns the [`schema`](#schema) method, since metadata is action specific and not shared with other actions. As of now, the only data you can pass in is the `actionName`, but that could be extended in the future. You can then access it in the `middlewareFn` passed to [`use`](#use) and in [`serverCodeFn`](#servercodefn) passed to [`define`](#define).
`metadata` expects an object of type [`ActionMetadata`](/docs/types#actionmetadata) that lets you specify useful data about the safe action you're defining, and it returns the [`schema`](#schema) method, since metadata is action specific and not shared with other actions. As of now, the only data you can pass in is the `actionName`, but that could be extended in the future. You can then access it in the `middlewareFn` passed to [`use`](#use) and in [`serverCodeFn`](#servercodefn) passed to [`action`](#action).

## `schema`

```typescript
schema<const S extends Schema>(schema: S) => { define(), bindArgsSchemas() }
schema<const S extends Schema>(schema: S) => { action(), bindArgsSchemas() }
```

`schema` accepts an input schema of type `Schema` (from TypeSchema), which is used to define the arguments that the safe action will receive, and returns the [`define`](#define) and [`bindArgsSchemas`](#bindargsschemas) methods, which allows you, respectively, to define a new action using that input schema or extend the arguments with additional bound ones.
`schema` accepts an input schema of type `Schema` (from TypeSchema), which is used to define the arguments that the safe action will receive, and returns the [`action`](#action) and [`bindArgsSchemas`](#bindargsschemas) methods, which allows you, respectively, to define a new action using that input schema or extend the arguments with additional bound ones.

## `bindArgsSchemas`

```typescript
bindArgsSchemas<const BAS extends Schema[]>(bindArgsSchemas: BAS) => { define() }
bindArgsSchemas<const BAS extends Schema[]>(bindArgsSchemas: BAS) => { action() }
```

`bindArgsSchemas` accepts an array of bind input schemas of type `Schema` (from TypeSchema), which is used to define the bind arguments that the safe action will receive, and returns the [`define`](#define) method, which allows you, to define a new action using the input and bind inputs schemas.
`bindArgsSchemas` accepts an array of bind input schemas of type `Schema` (from TypeSchema), which is used to define the bind arguments that the safe action will receive, and returns the [`action`](#action) method, which allows you, to define a new action using the input and bind inputs schemas.

## `define`
## `action`

```typescript
define<const Data = null>(serverCodeFn: ServerCodeFn<S, Data, Ctx>) => SafeActionFn<S, Data>
action<const Data = null>(serverCodeFn: ServerCodeFn<S, Data, Ctx>) => SafeActionFn<S, Data>
```

`define` is the final method in the list. It accepts a [`serverCodeFn`](#servercodefn) of type [`ServerCodeFn`](/docs/types#servercodefn) and returns a new safe action function of type [`SafeActionFn`](/docs/types#safeactionfn), which can be called from your components.
`action` is the final method in the list. It accepts a [`serverCodeFn`](#servercodefn) of type [`ServerCodeFn`](/docs/types#servercodefn) and returns a new safe action function of type [`SafeActionFn`](/docs/types#safeactionfn), which can be called from your components.

When the action is executed, all middleware functions in the chain will be called at runtime, in the order they were defined.

Expand Down
2 changes: 1 addition & 1 deletion website/docs/usage/bind-arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const onboardUser = action
z.string().uuid(),
z.number().min(18).max(150),
])
.define(
.action(
async ({
parsedInput: { username },
bindArgsParsedInputs: [userId, age],
Expand Down
2 changes: 1 addition & 1 deletion website/docs/usage/client-components/hooks/useaction.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const schema = z.object({

export const greetUser = actionClient
.schema(schema)
.define(async ({ parsedInput: { name } }) => {
.action(async ({ parsedInput: { name } }) => {
return { message: `Hello ${name}!` };
});
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const getLikes = () => likes;

export const addLikes = actionClient
.schema(schema)
.define(async ({ parsedInput: { amount } }) => {
.action(async ({ parsedInput: { amount } }) => {
await new Promise((resolve) => setTimeout(resolve, 1000));

// Mutate data in fake db. This would be a database call in the real world.
Expand Down
2 changes: 1 addition & 1 deletion website/docs/usage/custom-validation-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import { action } from "@/lib/safe-action";
// Here we're using the same schema declared above.
const signupAction = actionClient
.schema(schema)
.define(async ({ parsedInput: { email } }) => {
.action(async ({ parsedInput: { email } }) => {
// Assume this is a database call.
if (!isEmailAvailable(email)) {
returnValidationErrors(schema, {
Expand Down
2 changes: 1 addition & 1 deletion website/docs/usage/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const schema = zfd.formData({

export const signup = action
.schema(schema)
.define(async ({ email, password }) => {
.action(async ({ email, password }) => {
console.log("Email:", email, "Password:", password);
// Do something useful here.
});
Expand Down
4 changes: 2 additions & 2 deletions website/docs/usage/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const editProfile = authActionClient
// Here we pass the input schema.
.schema(z.object({ newUsername: z.string() }))
// Here we get `userId` from the middleware defined in `authActionClient`.
.define(async ({ parsedInput: { newUsername }, ctx: { userId } }) => {
.action(async ({ parsedInput: { newUsername }, ctx: { userId } }) => {
await saveNewUsernameInDb(userId, newUsername);

return {
Expand Down Expand Up @@ -141,7 +141,7 @@ const deleteUser = authActionClient
})
.metadata({ actionName: "deleteUser" })
.schema(z.void())
.define(async ({ ctx: { userId } }) => {
.action(async ({ ctx: { userId } }) => {
// Here we're sure that the user that is performing this operation is an admin.
await deleteUserFromDb(userId);
});
Expand Down

0 comments on commit 1617d22

Please sign in to comment.