kwhitley / itty-router

A little router.
MIT License
1.71k stars 77 forks source link

Documentation for module syntax 'context' parameter #93

Closed jcapogna closed 2 years ago

jcapogna commented 2 years ago

In the module syntax portion of the readme (https://github.com/kwhitley/itty-router#cf-es6-module-syntax), it has the following example of how to access the request and env bindings params:

router.get('/', (request, env) => {
  // now have access to the env (where CF bindings like durables, KV, etc now are)
})

I'm assuming there is a third context parameter for passing in the context (see: https://developers.cloudflare.com/workers/runtime-apis/fetch-event#syntax-module-worker), so the example should really be:

router.get('/', (request, env, context) => {
  // now have access to the env (where CF bindings like durables, KV, etc now are)
})

Is this correct?

kwhitley commented 2 years ago

You're correct! Didn't see the change to the CF API (I guess to enable waitUntil and such), but it should pass context through with no issue, as long as you use one of the formats below (all params passed to the router.handle() are passed to each handler in turn).

import { Router } from 'itty-router'
import { error } from 'itty-router-extras'

const router = Router()

router.get('/foo', (request, env, context) => {
  // all three arrive
})

// simple module version
export default {
  fetch: router.handle, // CF passes request, env, and context to this function
}

// more-control module version
export default {
  fetch: (...args) => router
                        .handle(...args)
                        .then(response => {
                           // modify response, e.g. CORS

                           return response
                        })
                        .catch(error)
}
kwhitley commented 2 years ago

I'll update the docs to reflect this change (unless you want to PR) - thanks for the heads up!

kwhitley commented 2 years ago

Updated in the docs as of 2.5.1, credit added to README and CHANGELOG. Thanks!! :)