TheEdoRan / next-safe-action

Type safe and validated Server Actions in your Next.js (App Router) project.
https://next.next-safe-action.dev
BSD 3-Clause "New" or "Revised" License
1.38k stars 26 forks source link

feat: add ability to wrap execution of server actions #84

Closed ludwigbacklund closed 1 month ago

ludwigbacklund commented 2 months ago

Adds the ability to wrap the execution of server actions by passing in a "wrapExecution" function when creating the safe action client where you can inject things like logging, tracing or performance monitoring. To do these things you also want the name of the action, which I've passed in via the utils object in this PR. This is backwards compatible without breaking changes.

Optimally I think this kind of functionality would best be implemented by changing the current middleware approach to one more similar to what playwright does with their fixtures but that would be a breaking change.

Written blind to get feedback before committing too much time, this has not yet been tested.

Example usage:

const performanceAction = createSafeActionClient({
  async wrapExecution(serverCode, parsedInput, ctx, actionName) {
    const t1 = performance.now();
    const res = await serverCode(parsedInput, ctx);
    const t2 = performance.now();

    // Prints 'Action "someAction" took 1000 milliseconds.'
    console.log(`Action "${actionName}" took ${t2 - t1} milliseconds.`);

    return res;
  },
});

const someAction = performanceAction(
  {
    name: z.string(),
  },
  async (input, ctx) => {
    await new Promise((resolve) => setTimeout(resolve, 1000));
  },
  {
    actionName: "someAction",
  }
);
vercel[bot] commented 2 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-safe-action-example-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2024 11:04pm
next-safe-action-website ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2024 11:04pm
TheEdoRan commented 2 months ago

Version 7 will include a much more powerful middleware system, kinda like the tRPC one. It should also cover all the use cases described in this PR. Please let me know what you think about it, thank you! Discussion here: #88