Skip to content

Commit

Permalink
fix: "empty response" handlers cannot return a response (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
christoph-fricke committed Oct 28, 2023
1 parent cb59a5d commit 2931f0c
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 8 deletions.
15 changes: 15 additions & 0 deletions .changeset/big-coats-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"openapi-msw": patch
---

Fixed OpenAPI operations with no-content responses cannot return a response. Now they are required to return an empty response, i.e. `null` as response body.

```typescript
const http = createOpenApiHttp<paths>();

// Resolver function is required to return a `StrictResponse<null>` (empty response)
// if the OpenAPI operation specifies `content?: never` for the response.
const noContent = http.delete("/resource", ({ params }) => {
return HttpResponse.json(null, { status: 204 });
});
```
17 changes: 14 additions & 3 deletions src/type-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,24 @@ export type ResponseBody<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
responses: any;
}
? FilterKeys<
SuccessResponse<ResponseObjectMap<ApiSpec[Path][Method]>>,
MediaType
? ConvertNoContent<
FilterKeys<
SuccessResponse<ResponseObjectMap<ApiSpec[Path][Method]>>,
MediaType
>
>
: never
: never;

/**
* OpenAPI-TS generates "no content" with `content?: never`.
* However, `new Response().body` is `null` and strictly typing no-content in MSW requires `null`.
* Therefore, this helper maps no-content to `null`.
*/
export type ConvertNoContent<Content> = [Content] extends [never]
? null
: Content;

/** MSW http handler factory with type inference for provided api paths. */
export type HttpHandlerFactory<
ApiSpec extends AnyApiSpec,
Expand Down
4 changes: 3 additions & 1 deletion tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
"outDir": "./dist",
"declaration": true,
"sourceMap": true
},
"include": ["src", "exports"],
"exclude": ["**/*.test.*"]
Expand Down
4 changes: 0 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@
"isolatedModules": true,
"resolveJsonModule": true,

/* Emit */
"declaration": true,
"sourceMap": true,

/* Type Checking */
"forceConsistentCasingInFileNames": true,
"strict": true,
Expand Down

0 comments on commit 2931f0c

Please sign in to comment.