Skip to content

Commit

Permalink
fix: allow returning Response objects from function Handlers
Browse files Browse the repository at this point in the history
Per the [functions documentation][1], it seems like you should be able
to return a standard `Response` object from function handlers. However,
the existing types only allows a user to return a `HandlerResponse`
object.

This updates the Handler type to accept both types as a return value.

(It looks like netlify#351 also
addresses this issue, but that PR is a little stale at this point.)

[1]: https://docs.netlify.com/functions/get-started/?fn-language=ts#synchronous-function
  • Loading branch information
ndhoule committed Jan 18, 2024
1 parent 3ce8520 commit 1f47afe
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/function/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import type { HandlerContext } from './handler_context.js'
import type { HandlerEvent } from './handler_event.js'
import type { HandlerResponse, BuilderResponse, StreamingResponse } from './handler_response.js'

export interface HandlerCallback<ResponseType extends HandlerResponse = HandlerResponse> {
export interface HandlerCallback<ResponseType extends HandlerResponse | Response = HandlerResponse> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error: any, response: ResponseType): void
}

export interface BaseHandler<
ResponseType extends HandlerResponse = HandlerResponse,
ResponseType extends HandlerResponse | Response = HandlerResponse,
C extends HandlerContext = HandlerContext,
> {
(event: HandlerEvent, context: C, callback?: HandlerCallback<ResponseType>): void | Promise<ResponseType>
Expand All @@ -18,7 +18,7 @@ export interface BackgroundHandler<C extends HandlerContext = HandlerContext> {
(event: HandlerEvent, context: C): void | Promise<void>
}

export type Handler = BaseHandler<HandlerResponse, HandlerContext>
export type Handler = BaseHandler<HandlerResponse | Response, HandlerContext>
export type BuilderHandler = BaseHandler<BuilderResponse, HandlerContext>

export interface StreamingHandler {
Expand Down
8 changes: 7 additions & 1 deletion test/types/Handler.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expectError } from 'tsd'
import { expectAssignable, expectError } from 'tsd'

import { Handler } from '../../src/main.js'

Expand All @@ -9,3 +9,9 @@ expectError(() => {
// void
}
})

expectAssignable<Handler>(() => Promise.resolve({ statusCode: 200 }));

expectAssignable<Handler>(() => Promise.resolve(new Response("hello")));

expectError<Handler>(() => Promise.resolve({ missing: "status code" }));

0 comments on commit 1f47afe

Please sign in to comment.