hey-api / openapi-ts

🚀 The OpenAPI to TypeScript codegen. Generate clients, SDKs, validators, and more. Support: @mrlubos
https://heyapi.dev
Other
1.39k stars 107 forks source link

Add a way to generate path types with params based on OpenAPI shema. #1314

Open mkeyy0 opened 1 day ago

mkeyy0 commented 1 day ago

Description

This feature request comes from this discussion #1157. So based on this discussion, it would be nice to add some way to get type-safe paths from OpenAPI schema. To be honest, I don't have exact thoughts on what API may look like because I don't have a lot of experience with type generation.

Just some thoughts that it could be some typed URL constructor or function that you can import from the generated result and use to construct the URL. Something like this:

// Generated from OpenAPI schema
type GeneratedPaths = {
  ['/api/v1/auth/login']: {
    params: {
      redirect_uri: string;
    };
  };
  ['/api/v1/auth/logout']: {
    params: {
      redirect_uri: string;
    };
  };
};

// exposed to the user
declare function buildURL<
  TPath extends keyof GeneratedPaths,
  TParams extends GeneratedPaths[TPath]['params'],
>(path: TPath, params: TParams): URL;

// Usage
buildURL('/api/v1/auth/login', { redirect_uri: 'https://example.com' }); // ok
buildURL('/api/v1/auth'); // type error (incorrect path)
buildURL('/api/v1/auth/logout', { redirect_url: 'https://example.com' }); // type error (incorrect params)

But it is just initial thoughts. But in general, it would be great to have!

mrlubos commented 1 day ago

Hey @mkeyy0, while this still isn't available, you can now create your own plugin for unsupported cases. See https://github.com/hey-api/openapi-ts/issues/1236#issuecomment-2463711707 for more info