kwhitley / itty-router

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

Add TResponse generic to Router type #129

Closed JustinGrote closed 1 year ago

JustinGrote commented 1 year ago

Now that the latest cloudlfare worker types supports doing everything in a non-global way, handle should be able to be scoped to just Promise<Response> per the fetch specification: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/#migrating-a-simple-worker

Right now, handle is hardcoded to return Promise<any> https://github.com/kwhitley/itty-router/blob/73659e875d31a487f0825b459142a41f5ec2cdc8/src/itty-router.d.ts#L45

Which results in a typescript error when passed to the module syntax worker:

import { ExportedHandler as Worker } from '@cloudflare/workers-types'
const router = Router<Response>()
const worker: Worker<any> = {
  fetch: router.handle
}
export default worker
//Type '(request: Response, ...extra: any) => Promise<any>' is not assignable to type 'ExportedHandlerFetchHandler<any>'.

And has to be forced currently.

Workaround

// Workaround for itty handler promise not being generic
const handleRequest: ExportedHandlerFetchHandler = async (
    request,
    env,
    ctx
) => {
    const response = await router.handle(request, env, ctx)
    if (!(response instanceof Response)) {
        return new Response('A response was not provided by the handler', {
            status: 503,
        })
    }
    return response
}

const worker: Worker = {
    fetch: handleRequest,
}
export default worker
kwhitley commented 1 year ago

Any chance you could test the itty-router@next and see if this issue persists? If not, we can close this, as v3.0 should be rolling out any day now!

kwhitley commented 1 year ago

Closing this as version 3 is live with all new types. Let's start over and investigate with 3.x to see if this is still an issue!