Skip to content
This repository has been archived by the owner on Nov 12, 2024. It is now read-only.

Commit

Permalink
Fix swr config generic
Browse files Browse the repository at this point in the history
  • Loading branch information
htunnicliff committed Feb 20, 2024
1 parent 98bd9f9 commit c9b50ba
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ export function makeHookFactory<Paths extends {}>(
ErrorResponse<ResponseObjectMap<Req>>,
MediaType
>,
>(fetchOptions: Options | null, swrConfig?: SWRConfiguration<Data, Error>) {
Config extends SWRConfiguration<Data, Error>,
>(fetchOptions: Options | null, swrConfig?: Config) {
type Key = [typeof keyPrefix, Path, Options] | null;

return useSWR<Data, Error, Key>(
return useSWR<Data, Error, Key, Config>(
// SWR key is based on the path and fetch options
// keyPrefix keeps each API's cache separate in case there are path collisions
fetchOptions ? [keyPrefix, path, fetchOptions] : null,
Expand Down
27 changes: 23 additions & 4 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import createClient from "openapi-fetch";
import type { paths } from "../petstore";
import type { paths } from "../generated/petstore";
import { makeHookFactory } from "../src/index";

import { expectTypeOf } from "expect-type";
import { SuccessResponseJSON } from "openapi-typescript-helpers";

const petStoreApi = createClient<paths>({
baseUrl: "https://petstore3.swagger.io/api/v3",
Expand All @@ -12,14 +13,32 @@ const petStoreHook = makeHookFactory<paths>(petStoreApi, "pet-store");

const useOrder = petStoreHook("/store/order/{orderId}");

type OrderSuccessResponse = SuccessResponseJSON<
paths["/store/order/{orderId}"]["get"]
>;

// Test regular hook
const { data } = useOrder({
params: {
path: { orderId: 1 },
},
});

expectTypeOf(data).not.toEqualTypeOf<OrderSuccessResponse>();
expectTypeOf(data).toEqualTypeOf<undefined | OrderSuccessResponse>();

if (data) {
expectTypeOf(data).toEqualTypeOf<
paths["/store/order/{orderId}"]["get"]["responses"]["200"]["content"]["application/json"]
>();
expectTypeOf(data).toEqualTypeOf<OrderSuccessResponse>();
}

// Test suspense hook
const { data: suspenseData } = useOrder(
{
params: {
path: { orderId: 1 },
},
},
{ suspense: true }
);

expectTypeOf(suspenseData).toEqualTypeOf<OrderSuccessResponse>();
2 changes: 1 addition & 1 deletion test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "../tsconfig.json",
"include": ["./src/**/*", "**/*"],
"include": ["../src/**/*", "**/*"],
"compilerOptions": {
"noEmit": true
},
Expand Down

0 comments on commit c9b50ba

Please sign in to comment.