kwhitley / itty-router

A little router.
MIT License
1.78k stars 78 forks source link

Examples using Modules syntax of CF worker scripts #55

Closed toinbis closed 2 years ago

toinbis commented 3 years ago

Would love to see an example of itty router being used in Modules syntax.

Thanks

kwhitley commented 3 years ago

Hey there!

I have a simple example on the README already: image

I'll add it (with link) to the features or description though.

So in modules, nothing really changes except the worker export/fetch signature... and because itty naturally passes any additional arguments that handle is called with into the request handlers themselves, it works perfectly with the "new" signature. :)

kwhitley commented 3 years ago

TODO: add to features list for quick reference

toinbis commented 3 years ago

I'll just add a note here that I succesfully managed to use itty-router in cf worker script written using ES6 Module Syntax.

src/index.ts:

import { worker } from './worker'
export default worker

src/worker.ts:

import { router } from './router'

// type from https://github.com/cloudflare/workers-types/blob/b1126ca31d2dc6e69d27dae740a7ffbcc0c8acd7/index.d.ts#L734
const worker: ModuleWorker = {
  fetch: router.handle
}

export { worker }

Thanks a lot @kwhitley !

kwhitley commented 3 years ago

Awesome @toinbis - glad to here it! I was happy to see (purely by luck) the (request, ...anything) interface we picked for itty's handlers, although slightly different from the familiar (request, response, next) pattern of express, worked flawlessly with CF's decision to pass the env as an additional params, where other libraries adhering more strictly to express patterns don't seem immediately compatible with the new module syntax.

Happy little accident! #bobross

toinbis commented 3 years ago

Interesting insight, thanks for sharing @kwhitley ! I think this issue can be considered as worth closing by now - but am kindly leaving this decision for you! :)

Thanks again for creating itty router!

Mecanik commented 2 years ago

I'll just add a note here that I succesfully managed to use itty-router in cf worker script written using ES6 Module Syntax.

src/index.ts:

import { worker } from './worker'
export default worker

src/worker.ts:

import { router } from './router'

// type from https://github.com/cloudflare/workers-types/blob/b1126ca31d2dc6e69d27dae740a7ffbcc0c8acd7/index.d.ts#L734
const worker: ModuleWorker = {
  fetch: router.handle
}

export { worker }

Thanks a lot @kwhitley !

For me, it says: "TS2304: Cannot find name 'ModuleWorker'". What else did you do?