-
-
Notifications
You must be signed in to change notification settings - Fork 286
-
Which scope/s are relevant/related to the feature request?
Don't know / other
Information
Hi,
I'm currently using AnalogJS for some of my projects, and I really appreciate its capabilities! Since the Nitro server already generates information about API routes, I was wondering if it would be possible to extend the HTTP client to provide type-safe requests, similar to how $fetch works in Nuxt.
To explore this idea, I created a small example where I wrapped HttpClient to support typed API routes automatically. This approach enhances developer experience by enabling autocomplete for API endpoints and strict type safety for responses.
type ApiRoutes = keyof InternalApi; type ApiResponse<TPath extends ApiRoutes> = InternalApi[TPath]['default']; @Injectable({ providedIn: 'root' }) export class $HttpClient { #httpClient = inject(HttpClient); #apiPrefix = injectAPIPrefix(); get<TPath extends ApiRoutes>( path: TPath, options?: { .... } ): Observable<ApiResponse<TPath>> { return this.#httpClient.get<ApiResponse<TPath>>(`${this.#apiPrefix}${path}`, options); } post<TPath extends ApiRoutes>( path: TPath, body: any, options?: { .... } ): Observable<ApiResponse<TPath>> { return this.#httpClient.post<ApiResponse<TPath>>(`${this.#apiPrefix}${path}`, body, options); } }
To make this work, I need to include the generated Nitro route types using:
/// <reference path="../dist/.nitro/types/nitro.d.ts" />
With this setup, I can inject $HttpClient and get code completion for API routes as well as automatic type resolution based on the selected route.
Usage: inject($HttpClient).get('/v1/example')
Would this be something worth integrating into AnalogJS?
Let me know what you think! 🚀
Describe any alternatives/workarounds you're currently using
No response
I would be willing to submit a PR to fix this issue
- Yes
- No
Beta Was this translation helpful? Give feedback.