kwhitley / itty-router

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

HTTP Headers on IRequest #143

Closed sdorazio closed 1 year ago

sdorazio commented 1 year ago

The new IRequest interface should expose HTTP request headers as a property.

chmac commented 1 year ago

Agreed. I presumed from the types that the .headers property was absent. But my tests indicate it exists. Would be great if the types were in sync.

For anyone who finds this struggling to access the headers, I've used a hack like so:

const auth = (request as any).headers.get('Authorization');

There's undoubtedly a better type, but this was the quickest option and it works for my use case.

chmac commented 1 year ago

I think there's also other undocumented methods on IRequest, for example request.json(). Would it make sense to open a new issue to track that? Or could we update this issue to be about suggesting that IRequest extends the base Request type?

mhujer commented 1 year ago

My workaround to get the missing things from Request back is to add & Request to the handler, so I get proper autocompletion:


import type { Request } from '@cloudflare/workers-types';

async function handleCreateComment(request: IRequest & Request, env: Env) {
     const requestData = await request.json<CreateCommentRequest>(); // this works again

The only downside so far is that I had to add ignore to the route definition because of incompatible types:

// @ts-expect-error eslint-disable-line @typescript-eslint/ban-ts-comment
router.post('/:siteId', handleCreateComment);
KamaniBhavin commented 1 year ago

My workaround to get the missing things from Request back is to add & Request to the handler, so I get proper autocompletion:

import type { Request } from '@cloudflare/workers-types';

async function handleCreateComment(request: IRequest & Request, env: Env) {
     const requestData = await request.json<CreateCommentRequest>(); // this works again

The only downside so far is that I had to add ignore to the route definition because of incompatible types:

// @ts-expect-error eslint-disable-line @typescript-eslint/ban-ts-comment
router.post('/:siteId', handleCreateComment);

In my situation, I need to access the .formData() method, which is not accessible on IRequest. It could be helpful to add additional methods to IRequest.

maccman commented 1 year ago

I would suggest that iRequest shouldn't exist. I would just use the native request.

kwhitley commented 1 year ago

Got you covered in next/52 :)

IRequest now unions native Request, allowing expected request typing :)

Check out the massive changes here: https://itty.dev/itty-router/typescript

kwhitley commented 1 year ago

Additionally for the sadists, IRequestStrict also now exists, removing the generic traps.

kwhitley commented 1 year ago

The new IRequest interface should expose HTTP request headers as a property.

Done! :)

chmac commented 1 year ago

@kwhitley That's frickin awesome, thank you.