Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(types): type $fetch to match json serialization output #1002

Merged
merged 6 commits into from
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/types/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { RouterMethod } from "h3";
import type { FetchRequest, FetchOptions, FetchResponse } from "ofetch";
import type { Serialize, Simplify } from "./serialize";
import type { MatchedRoutes } from "./utils";

// An interface to extend in a local project
Expand All @@ -16,7 +17,11 @@ export type MiddlewareOf<
Route extends string,
Method extends RouterMethod | "default"
> = Method extends keyof InternalApi[MatchedRoutes<Route>]
? Exclude<InternalApi[MatchedRoutes<Route>][Method], Error | void>
? Simplify<
Serialize<
Exclude<InternalApi[MatchedRoutes<Route>][Method], Error | void>
>
>
: never;

export type TypedInternalResponse<
Expand Down
56 changes: 56 additions & 0 deletions src/types/serialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* @link https://github.com/remix-run/remix/blob/2248669ed59fd716e267ea41df5d665d4781f4a9/packages/remix-server-runtime/serialize.ts
*/
type JsonPrimitive =
| string
| number
| boolean
// eslint-disable-next-line @typescript-eslint/ban-types
| String
// eslint-disable-next-line @typescript-eslint/ban-types
| Number
// eslint-disable-next-line @typescript-eslint/ban-types
| Boolean
| null;
// eslint-disable-next-line @typescript-eslint/ban-types
type NonJsonPrimitive = undefined | Function | symbol;

/*
* `any` is the only type that can let you equate `0` with `1`
* See https://stackoverflow.com/a/49928360/1490091
*/
type IsAny<T> = 0 extends 1 & T ? true : false;

type FilterKeys<TObj extends object, TFilter> = {
[TKey in keyof TObj]: TObj[TKey] extends TFilter ? TKey : never;
}[keyof TObj];

// prettier-ignore
export type Serialize<T> =
IsAny<T> extends true ? any :
T extends JsonPrimitive ? T :
T extends Map<any,any> | Set<any> ? Record<string, never> :
T extends NonJsonPrimitive ? never :
T extends { toJSON(): infer U } ? U :
T extends [] ? [] :
T extends [unknown, ...unknown[]] ? SerializeTuple<T> :
T extends ReadonlyArray<infer U> ? (U extends NonJsonPrimitive ? null : Serialize<U>)[] :
T extends object ? SerializeObject<T> :
never;

/** JSON serialize [tuples](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) */
type SerializeTuple<T extends [unknown, ...unknown[]]> = {
[k in keyof T]: T[k] extends NonJsonPrimitive ? null : Serialize<T[k]>;
};

/** JSON serialize objects (not including arrays) and classes */
type SerializeObject<T extends object> = {
[k in keyof Omit<T, FilterKeys<T, NonJsonPrimitive>>]: Serialize<T[k]>;
};

/**
* @see https://github.com/ianstormtaylor/superstruct/blob/7973400cd04d8ad92bbdc2b6f35acbfb3c934079/src/utils.ts#L323-L325
*/
export type Simplify<TType> = TType extends any[] | Date
? TType
: { [K in keyof TType]: TType[K] };
1 change: 1 addition & 0 deletions test/fixture/api/serialized/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default defineEventHandler(() => ({ createdAt: new Date() }));
3 changes: 3 additions & 0 deletions test/fixture/api/serialized/function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default defineEventHandler(() => {
return { foo: () => 'foo' }
});
3 changes: 3 additions & 0 deletions test/fixture/api/serialized/map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default defineEventHandler(() => {
return { foo: new Map<string, number>([["key", 2]]) };
});
3 changes: 3 additions & 0 deletions test/fixture/api/serialized/set.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default defineEventHandler(() => {
return { foo: new Set(["item"]) };
});
3 changes: 3 additions & 0 deletions test/fixture/api/serialized/tuple.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default defineEventHandler(() => {
return ["foo", new Date()] as [string, Date];
});
28 changes: 28 additions & 0 deletions test/fixture/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,32 @@ describe("API routes", () => {
$fetch("/api/methods/default", { method: "POST" })
).toMatchTypeOf<Promise<"Default override">>();
});

it("generates types matching JSON serialization output", () => {
expectTypeOf($fetch("/api/serialized/date")).toMatchTypeOf<
Promise<{
createdAt: string;
}>
>();

expectTypeOf($fetch("/api/serialized/function")).toMatchTypeOf<
Promise<object>
>();

expectTypeOf($fetch("/api/serialized/map")).toMatchTypeOf<
Promise<{
foo: Record<string, never>;
}>
>();

expectTypeOf($fetch("/api/serialized/set")).toMatchTypeOf<
Promise<{
foo: Record<string, never>;
}>
>();

expectTypeOf($fetch("/api/serialized/tuple")).toMatchTypeOf<
Promise<[string, string]>
>();
});
});