-
-
Notifications
You must be signed in to change notification settings - Fork 805
Expose a type infered from route response based on route name (NitroFetchRequest) and http method #3355
Copy link
Copy link
Closed as duplicate of#2758
Labels
Description
Describe the feature
I wrote a custom FormWrapper component in Vue (nuxt) that takes a validation schema as parameter to validate the form before to submit it (mainly working with inject and provide).
<FormWrapper :schema :submitInfo @onFormSubmitSuccess="onFormSubmitSuccess">
<FormInputText name="title" label="Title" type="text" placeholder="Book's title" autocomplete="off" />
<FormInputText name="author" label="Book's author" type="text" placeholder="Jeanne Doe" autocomplete="off" />
<FormButton class="self-end w-fit">Add new book</FormButton>
<FormApiErrorText class="self-end text-end" />
</FormWrapper>
<script lang="ts" setup>
//Form
const schema = z.object({ title : z.string(), author : z.string() });
const submitInfo: FormNitroSubmitInfoType = {
httpMethod: "POST",
endpoint: "/api/user/book/add"
};
//Success callback
function onFormSubmitSuccess(info: FormOnFormSubmitSuccessResponse<typeof schema, "/api/user/book/add", "post">) {
console.log("Success !");
}
</script>The issue is that I needed to write infered type from nitropack available type with some trickshots:
import type { AvailableRouterMethod, NitroFetchOptions, NitroFetchRequest } from "nitropack";
//Components types
export type HTTP_METHOD_TYPE = "GET" | "POST" | "PUT" | "DELETE";
export type ZodInstanceOf<T extends z.ZodType<any, any, any>> = z.infer<T>;
export type FormNitroSubmitInfoType = { httpMethod: HTTP_METHOD_TYPE; endpoint: NitroFetchRequest };
export type FormNonPrefillableFields = string[]; //Default is captcha
//Trickshots for return inference
export type FormNitroResponseType<R extends NitroFetchRequest, Y extends AvailableRouterMethod<R>> = Awaited<ReturnType<typeof $fetch<unknown, R, { method: Y } & NitroFetchOptions<R, Y>>>>;
export type FormOnFormSubmitSuccessResponse<X extends z.ZodType<any, any, any>, R extends NitroFetchRequest, Y extends AvailableRouterMethod<R>> = {
payload: ZodInstanceOf<X>;
response: FormNitroResponseType<R, Y>;
};Resulting in sometimes: error TS2321: Excessive stack depth comparing types;
Feature
Is it possible for NitroPack to expose a type that directly resolves to the return type of a specified API endpoint? (based on api route and http method).
It's basically the one return by $fetch.
Something like:
import type { NitroFetchResponse } from "nitropack";
const response: NitroFetchResponse<"/api/admin/charmap/replacements", "post"> = ...This would helps a lot to use the inferred type provided from nitropack / h3 /nuxt.
Is there perhaps an alternative way to achieve this?
Additional information
- Would you be willing to help implement this feature?
Reactions are currently unavailable