Skip to content

Commit

Permalink
feat: add support for additional response resolver info (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
christoph-fricke committed Dec 21, 2023
1 parent ad8d2d1 commit 07fa9b0
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 80 deletions.
5 changes: 5 additions & 0 deletions .changeset/modern-seals-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-msw": minor
---

Restructured the library to add support for additional response resolver info. The enhanced `ResponseResolver` type and `ResponseResolverInfo` are available as exports.
17 changes: 11 additions & 6 deletions exports/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
export { createOpenApiHttp } from "../src/openapi-http.js";
export type { HttpOptions, OpenApiHttpHandlers } from "../src/openapi-http.js";
export type { AnyApiSpec, HttpMethod } from "../src/api-spec.js";

export {
createOpenApiHttp,
type HttpHandlerFactory,
type HttpOptions,
type OpenApiHttpHandlers,
} from "../src/openapi-http.js";

export type {
AnyApiSpec,
HttpHandlerFactory,
HttpMethod,
} from "../src/type-helpers.js";
ResponseResolver,
ResponseResolverInfo,
} from "../src/response-resolver.js";
50 changes: 6 additions & 44 deletions src/type-helpers.ts → src/api-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
ResponseObjectMap,
SuccessResponse,
} from "openapi-typescript-helpers";
import type { http } from "msw";
import type { ConvertToStringified } from "./type-utils.js";

/** Base type that any api spec should extend. */
export type AnyApiSpec = NonNullable<unknown>;
Expand All @@ -27,7 +27,7 @@ export type PathsForMethod<
Method extends HttpMethod,
> = PathsWithMethod<ApiSpec, Method>;

/** Extract the params of a given path and method from an api spec. */
/** Extract the path params of a given path and method from an api spec. */
export type PathParams<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Expand All @@ -37,14 +37,10 @@ export type PathParams<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
parameters: { path: any };
}
? ConvertToStringLike<ApiSpec[Path][Method]["parameters"]["path"]>
? ConvertToStringified<ApiSpec[Path][Method]["parameters"]["path"]>
: never
: never;

type ConvertToStringLike<Params> = {
[Name in keyof Params]: Params[Name] extends string ? Params[Name] : string;
};

/** Extract the request body of a given path and method from an api spec. */
export type RequestBody<
ApiSpec extends AnyApiSpec,
Expand Down Expand Up @@ -75,41 +71,7 @@ export type ResponseBody<

/**
* 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`.
* 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,
Method extends HttpMethod,
> = <Path extends PathsForMethod<ApiSpec, Method>>(
path: Path,
resolver: ResponseResolver<ApiSpec, Path, Method>,
options?: RequestHandlerOptions,
) => ReturnType<typeof http.all>;

/** MSW handler options. */
export type RequestHandlerOptions = Required<Parameters<typeof http.all>[2]>;

/** MSW response resolver function that is made type-safe through an api spec. */
export interface ResponseResolver<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
> extends ResponseResolverType<ApiSpec, Path, Method> {}

type ResponseResolverType<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
> = Parameters<
typeof http.all<
PathParams<ApiSpec, Path, Method>,
RequestBody<ApiSpec, Path, Method>,
ResponseBody<ApiSpec, Path, Method>
>
>[1];
type ConvertNoContent<Content> = [Content] extends [never] ? null : Content;
18 changes: 14 additions & 4 deletions src/openapi-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { describe, expect, it, vi } from "vitest";
import { http as mswHttp } from "msw";
import { createOpenApiHttp } from "./openapi-http.js";
import type { HttpMethod } from "./type-helpers.js";
import type { HttpMethod } from "./api-spec.js";

const methods: HttpMethod[] = [
"get",
Expand Down Expand Up @@ -40,7 +40,9 @@ describe.each(methods)("openapi %s http handlers", (method) => {
http[method]("/test", resolver, { once: false });

expect(spy).toHaveBeenCalledOnce();
expect(spy).toHaveBeenCalledWith("/test", resolver, { once: false });
expect(spy).toHaveBeenCalledWith("/test", expect.any(Function), {
once: false,
});
});

it("should convert openapi paths to MSW compatible paths", () => {
Expand All @@ -51,7 +53,11 @@ describe.each(methods)("openapi %s http handlers", (method) => {
http[method]("/test/{id}", resolver);

expect(spy).toHaveBeenCalledOnce();
expect(spy).toHaveBeenCalledWith("/test/:id", resolver, undefined);
expect(spy).toHaveBeenCalledWith(
"/test/:id",
expect.any(Function),
undefined,
);
});

it("should prepend a configured baseUrl to the path for MSW", () => {
Expand All @@ -62,6 +68,10 @@ describe.each(methods)("openapi %s http handlers", (method) => {
http[method]("/test", resolver);

expect(spy).toHaveBeenCalledOnce();
expect(spy).toHaveBeenCalledWith("*/api/rest/test", resolver, undefined);
expect(spy).toHaveBeenCalledWith(
"*/api/rest/test",
expect.any(Function),
undefined,
);
});
});
64 changes: 38 additions & 26 deletions src/openapi-http.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,35 @@
import { http } from "msw";
import { http, type RequestHandlerOptions } from "msw";
import type { AnyApiSpec, HttpMethod, PathsForMethod } from "./api-spec.js";
import { convertToColonPath } from "./path-mapping.js";
import type {
AnyApiSpec,
HttpHandlerFactory,
HttpMethod,
} from "./type-helpers.js";
import {
createResolverWrapper,
type ResponseResolver,
} from "./response-resolver.js";

/** HTTP handler factory with type inference for provided api paths. */
export type HttpHandlerFactory<
ApiSpec extends AnyApiSpec,
Method extends HttpMethod,
> = <Path extends PathsForMethod<ApiSpec, Method>>(
path: Path,
resolver: ResponseResolver<ApiSpec, Path, Method>,
options?: RequestHandlerOptions,
) => ReturnType<typeof http.all>;

function createHttpWrapper<
ApiSpec extends AnyApiSpec,
Method extends HttpMethod,
>(
method: Method,
httpOptions?: HttpOptions,
): HttpHandlerFactory<ApiSpec, Method> {
return (path, resolver, options) => {
const mswPath = convertToColonPath(path as string, httpOptions?.baseUrl);
const mswResolver = createResolverWrapper(resolver);

return http[method](mswPath, mswResolver, options);
};
}

/** Collection of enhanced HTTP handler factories for each available HTTP Method. */
export type OpenApiHttpHandlers<ApiSpec extends AnyApiSpec> = {
Expand Down Expand Up @@ -41,26 +66,13 @@ export function createOpenApiHttp<ApiSpec extends AnyApiSpec>(
options?: HttpOptions,
): OpenApiHttpHandlers<ApiSpec> {
return {
get: createHttpWrapper<ApiSpec, "get">("get", options),
put: createHttpWrapper<ApiSpec, "put">("put", options),
post: createHttpWrapper<ApiSpec, "post">("post", options),
delete: createHttpWrapper<ApiSpec, "delete">("delete", options),
options: createHttpWrapper<ApiSpec, "options">("options", options),
head: createHttpWrapper<ApiSpec, "head">("head", options),
patch: createHttpWrapper<ApiSpec, "patch">("patch", options),
get: createHttpWrapper("get", options),
put: createHttpWrapper("put", options),
post: createHttpWrapper("post", options),
delete: createHttpWrapper("delete", options),
options: createHttpWrapper("options", options),
head: createHttpWrapper("head", options),
patch: createHttpWrapper("patch", options),
untyped: http,
};
}

function createHttpWrapper<
ApiSpec extends AnyApiSpec,
Method extends HttpMethod,
>(
method: Method,
httpOptions?: HttpOptions,
): HttpHandlerFactory<ApiSpec, Method> {
return (path, resolver, options) => {
const mswPath = convertToColonPath(path as string, httpOptions?.baseUrl);
return http[method](mswPath, resolver, options);
};
}
57 changes: 57 additions & 0 deletions src/response-resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { AsyncResponseResolverReturnType, http } from "msw";
import type {
AnyApiSpec,
HttpMethod,
PathParams,
RequestBody,
ResponseBody,
} from "./api-spec.js";

/** Response resolver that gets provided to HTTP handler factories. */
export type ResponseResolver<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
> = (
info: ResponseResolverInfo<ApiSpec, Path, Method>,
) => AsyncResponseResolverReturnType<ResponseBody<ApiSpec, Path, Method>>;

/** Response resolver info that extends MSW's resolver info with additional functionality. */
export interface ResponseResolverInfo<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
> extends MSWResponseResolverInfo<ApiSpec, Path, Method> {}

/** Wraps MSW's resolver function to provide additional info to a given resolver. */
export function createResolverWrapper<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
>(
resolver: ResponseResolver<ApiSpec, Path, Method>,
): MSWResponseResolver<ApiSpec, Path, Method> {
return (info) => {
return resolver(info);
};
}

/** MSW response resolver info that is made type-safe through an api spec. */
type MSWResponseResolverInfo<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
> = Parameters<MSWResponseResolver<ApiSpec, Path, Method>>[0];

/** MSW response resolver function that is made type-safe through an api spec. */
export type MSWResponseResolver<
ApiSpec extends AnyApiSpec,
Path extends keyof ApiSpec,
Method extends HttpMethod,
> = Parameters<
typeof http.all<
PathParams<ApiSpec, Path, Method>,
RequestBody<ApiSpec, Path, Method>,
ResponseBody<ApiSpec, Path, Method>
>
>[1];
7 changes: 7 additions & 0 deletions src/type-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** Converts a type to string while preserving string literal types. */
export type Stringify<Value> = Value extends string ? Value : string;

/** Converts a object values to their {@link Stringify} value. */
export type ConvertToStringified<Params> = {
[Name in keyof Params]: Stringify<Required<Params>[Name]>;
};
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"allowUnreachableCode": false,
"exactOptionalPropertyTypes": true,

/* Completeness */
"skipDefaultLibCheck": true,
Expand Down

0 comments on commit 07fa9b0

Please sign in to comment.