Uh oh!
There was an error while loading. Please reload this page.
refactor(nuxt): enhance useFetch and useLazyFetch request type - #4825
Conversation
Enhance the useFetch and useLazyFetch request's type by inferring nitropack's server route's string literal (InternalApi interface). supporting auto-complete and showing type hints.
✅ Deploy Preview for nuxt3-docs ready!
To edit notification comments on pull requests, go to your Netlify site settings. |
…zyFetch` #4823 add type tests to composables suite, calling useFetch with: 1. all routes generated from server, 2. external url, 3. Request object. And should throw type error when pass in invalid request string
Rigo-m
commented
May 5, 2022
One thing that's missing is the ability to type POST request body, is there a way to implement it? |
didavid61202
commented
May 5, 2022
@Rigo-m I'll look into this! |
Rigo-m
commented
May 5, 2022
Sorry that I can't help, I'm still bad a TS somehow hahaha |
Got a working code that infers the body type of a POST API, but still needs to manually export the type from the API file and change the auto-generated InternalApi interface, or have to make some change to nitropack (and maybe h3) to make the implementation cleaner. hacky method // .nuxt/types/nitro.d.tsdeclare module 'nitropack'{typeAwaited<T>=TextendsPromiseLike<infer U> ? Awaited<U> : TinterfaceInternalApi{// turn value of InternalApi in to tuple, with index 1 being the body type'/api/test': [Awaited<ReturnType<typeofimport('../../server/api/test').default>>,import('../../server/api/test').BodyType]'/__nuxt_error': [Awaited<ReturnType<typeofimport('../../../packages/nuxt/src/core/runtime/nitro/renderer').default>>,'']}}// server/api/test.tsexporttypeBodyType={tag:string,index:number}// export the manually defined typeexportdefaultdefineEventHandler(async(event)=>{constbody=awaituseBody<BodyType>(event)return{result: body.tag}})// composable/fetch.tsexportdeclaretypeFetchRequestUrl=Exclude<keyofInternalApi,'/__nuxt_error'>|(`${string}${'/'|'.'}${string}` &{})|Exclude<FetchRequest,string>interfaceExFetchOptions<RouteextendsFetchRequestUrl>extendsFetchOptions{body?: RouteextendskeyofInternalApi ? InternalApi[Route][1] : FetchOptions['body']}exportinterfaceUseFetchOptions<DataT,ReqTextendsFetchRequestUrl,Transformextends_Transform<DataT,any>=_Transform<DataT,DataT>,PickKeysextendsKeyOfRes<Transform>=KeyOfRes<Transform>>extendsAsyncDataOptions<DataT,Transform,PickKeys>,ExFetchOptions<ReqT>{key?: string}// usageconst{ data }=useFetch('/api/test',{// have to update nitropack's type to correctly infer data typemethod: 'POST',body: {tag: '3',index: 2}// body will be type 'BodyType '}) |
Rigo-m
commented
May 5, 2022
Maybe a clean solution could be manually typing body by extending nuxt schema like we do for manually tiping useRuntimeConfig? |
danielroe
commented
May 6, 2022
I love this idea. I think rather than seeking to implement within ... and then update this PR accordingly. WDYT @pi0? |
pi0
commented
May 6, 2022
I also love to try this idea! Indeed nitro seems better place to implement types for |
didavid61202
commented
May 6, 2022
Sounds great! I implement it in Nuxt first as I wasn't sure if this should be implemented in nitropack. But after some digging and trying to implement type hint for POST body yesterday, I also found out that the codes to updates are mostly in nitropack. mainly:
I'll find some time to dig into it 👍 |
Hey, @danielroe@pi0 would like to get some suggestions/notices (if any) on point 2 before I start, for changing the |
didavid61202
commented
May 7, 2022
UpdateImplementing this enhancement in |
pi0
commented
May 10, 2022
@didavid61202 Since nitrojs/nitro#208 is landed, do you mind to rework this PR? Thanks! |
didavid61202
commented
May 10, 2022
I'm on it! 🚀 |
pi0
commented
May 12, 2022
I would hide all |
updated in b49385c, excluding all |
pi0
commented
May 12, 2022
@didavid61202 Maybe we can move this fix directly to Nitro and avoid workaround? I can quickly merge it for nitro and this after that :) |
sure, on it! |
danielroe
commented
May 12, 2022
Looking great! There were a couple of workarounds in 7e89fe8 that I think we can now remove as well, if you're up for it 😊 |
Can we directly use |
sure, on it! will see what I can do 👍 |
got it! |
useFetch and useLazyFetch request type #4823useFetch and useLazyFetch request type #4823useFetch and useLazyFetch request type #4823useFetch and useLazyFetch request typeUh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
useFetch and useLazyFetch request typeuseFetch and useLazyFetch request typepi0
commented
Jul 25, 2022
Thanks for working on this @didavid61202@danielroe <3 |
Updates
awaiting fix in nitro for
NitroFetchRequesttype to support string type (FixNitroFetchRequesttype to supportstringtype nitrojs/nitro#225)update at 2022/5/11
updated this PR according to
unjs/nitro's newNitroFetchRequesttype (enhance $fetch's request type infer from generated InternalApi interface nitrojs/nitro#208)update at 2022/5/11
Implementing this enhancement in the
unjs/nitrorepo for$fetchfirst (enhance $fetch's request type infer from generated InternalApi interface nitrojs/nitro#208), and will update this PR accordingly.update at 2022/5/7
Enhance the useFetch and useLazyFetch request's type by inferring nitropack's server route's string literal (InternalApi interface). supporting auto-complete and showing type hints.
🔗 Linked issue
Resolvenuxt/nuxt#13934
❓ Type of change
📚 Description
Enhance the
useFetchanduseLazyFetchrequest's type by inferring nitropack's server route's string literal (InternalApi interface).This will provide better DX and prevent typos while using
useFetchanduseLazyFetchby supporting auto-complete and showing type hints when entering the request. And should still be able to pass other valid request URLs likehttps://example.com/apior Request object likenew Request('/api/test')Usage scenario
assume project contains
server/api/test.ts📝 Checklist