Skip to content

Commit

Permalink
expanded middleware example to include second middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
kwhitley committed Apr 2, 2024
1 parent a3d9181 commit 33d1ef6
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions examples/types/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ type UserRequest = {
user: string
} & IRequestStrict

type PetRequest = {
pet: string
} & IRequestStrict

// we define a *strict* router for this demo
const router = IttyRouter<IRequestStrict>()

Expand All @@ -13,15 +17,21 @@ const withUser: RequestHandler<UserRequest> = (request) => {
request.user = 'Kevin'
}

// middleware with explicit request-type (generic)
const withPet = (request: PetRequest) => {
request.pet = 'Halsey'
}

router
// request will be IRequestStrict here, thus no user property
.get('/', (request) => {
request.user = 'Kevin' // invalid
})

// then we add the middleware defined above, allowing the handler chain to inherit the request type
.all('*', withUser, (request) => {
request.user = 'Kevin'
.all<UserRequest & PetRequest>('*', withUser, withPet, (request) => {
request.user = 'Kevin' // should work
request.pet = 'Halsey' // should work
})

// request will be back to IRequestStrict here, thus no user property
Expand Down

0 comments on commit 33d1ef6

Please sign in to comment.