rexfordessilfie / nextwrappers

Reusable, composable middleware-like wrappers for Next.js App Router Route Handlers and Middleware.
MIT License
24 stars 0 forks source link

Explore adding a generic wrapper creator #19

Closed rexfordessilfie closed 1 year ago

rexfordessilfie commented 1 year ago

The middleware pattern for wrappers seems to be one that is occurring a lot in several contexts. So far, we have seen this in the OG Express application, Next.js API routes, the new Route Handlers and then now also with Server Actions.

This pattern is akin to the decorator pattern in Python as well. It might be worth exploring a generic way in which we can repeat this pattern across a different domains/types of functions and in a type-safe way.

Given a generic function such as the following, we want to create a wrapper that lets us:

  1. perform some operations before and after executing the function
  2. execute the wrapped function and return its value
  3. receive the same/unbounded number of arguments as the wrapped function might receive without knowing a-priori what arguments those might be. Previous patterns restrict this by having parameters of (req, res, next) for example, assuming there are only ever two arguments, which is true in some cases. An alternate ordering I have explored is (next, req, res) allowing the list of args to be arbitrary.
function myFunc(a:int, b:int) {
   return a + b
}

const myFuncB = wrapper(myFunc)

myFuncB(1, 2) // => 3
myFunc(1, 2) // => 3

Motivation

The motivation for exploring this pattern is to avoid some of the repetition that seems to be coming with defining wrappers for the App Router, and then the Pages Router and then soon for Server Actions.

rexfordessilfie commented 1 year ago

See: https://github.com/rexfordessilfie/nextwrappers/pull/20#issuecomment-1614071125