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(fetch): typed body/query options for $fetch #2405

Closed
wants to merge 3 commits into from
Closed
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
18 changes: 18 additions & 0 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export async function build(nitro: Nitro) {
export async function writeTypes(nitro: Nitro) {
const types: NitroTypes = {
routes: {},
handlers: {}
};

const typesDir = resolve(nitro.options.buildDir, "types");
Expand All @@ -131,6 +132,12 @@ export async function writeTypes(nitro: Nitro) {
types.routes[mw.route][method]!.push(
`Simplify<Serialize<Awaited<ReturnType<typeof import('${relativePath}').default>>>>`
);

types.handlers[mw.route] ??= {};
types.handlers[mw.route][method] ??= [];
types.handlers[mw.route][method]!.push(
`typeof import('${relativePath}').default`
);
}

let autoImportedTypes: string[] = [];
Expand Down Expand Up @@ -208,6 +215,17 @@ export async function writeTypes(nitro: Nitro) {
].join("\n")
),
" }",
" interface InternalApiHandlers {",
...Object.entries(types.handlers).map(([path, methods]) =>
[
` '${path}': {`,
...Object.entries(methods).map(
([method, types]) => ` '${method}': ${types.join(" | ")}`
),
" }",
].join("\n")
),
" }",
"}",
// Makes this a module for augmentation purposes
"export {}",
Expand Down
44 changes: 35 additions & 9 deletions src/types/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { RouterMethod } from "h3";
import type { EventHandler, EventHandlerRequest, RouterMethod } from "h3";
import type { FetchRequest, FetchOptions, FetchResponse } from "ofetch";
import type { MatchedRoutes } from "./utils";

// An interface to extend in a local project

// Interfaces to extend in a local project
export interface InternalApi {}
export interface InternalApiHandlers {}

export type NitroFetchRequest =
| Exclude<keyof InternalApi, `/_${string}` | `/api/_${string}`>
Expand Down Expand Up @@ -49,14 +49,40 @@ export type AvailableRouterMethod<R extends NitroFetchRequest> =
: RouterMethod
: RouterMethod;

// Argumented fetch options to include the correct request methods.
// This overrides the default, which is only narrowed to a string.
export interface NitroFetchOptions<
// Extracts the body or query parameter types expected for a route
// based on the types inferred from bodyValidator/queryValidator.
export type HandlerInputType<
R extends NitroFetchRequest,
M extends AvailableRouterMethod<R>,
P extends "body" | "query"
> =
R extends string
? keyof InternalApiHandlers[MatchedRoutes<R>] extends undefined
? any
: InternalApiHandlers[MatchedRoutes<R>][
Extract<
keyof InternalApiHandlers[MatchedRoutes<R>],
"default"
> extends undefined ? M : "default"
] extends EventHandler<EventHandlerRequest<infer Body, infer Query>>
? P extends "query" ? Query : Body
: any
: any;

// Argumented fetch options to include the correct request methods,
// body types, and query parameter types.
export type NitroFetchOptions<
R extends NitroFetchRequest,
M extends AvailableRouterMethod<R> = AvailableRouterMethod<R>,
> extends FetchOptions {
method?: Uppercase<M> | M;
}
> = Omit<FetchOptions, 'body' | 'query'> & (
M extends string
? {
method?: Uppercase<M> | M;
body?: HandlerInputType<R, M, "body">;
query?: HandlerInputType<R, M, "query">;
}
: never
);

// Extract the route method from options which might be undefined or without a method parameter.
export type ExtractedRouteMethod<
Expand Down
7 changes: 4 additions & 3 deletions src/types/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,10 @@ export type PrerenderGenerateRoute = PrerenderRoute;

type HookResult = void | Promise<void>;

export type NitroTypes = {
routes: Record<string, Partial<Record<RouterMethod | "default", string[]>>>;
};
export type NitroTypes = Record<
'routes' | 'handlers',
Record<string, Partial<Record<RouterMethod | "default", string[]>>>
>;

export interface NitroHooks {
"types:extend": (types: NitroTypes) => HookResult;
Expand Down