RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.69k stars 1.24k forks source link

Typescript Axios client should have the option to generate an Interface for optional parameters rather than inlining them #3485

Open hisuwh opened 3 years ago

hisuwh commented 3 years ago

I have many api endpoints in my application that look like this:

[HttpGet("{id}/something")]
public Task<PagedResult<SomethingDto>> GetSomething(int id, [FromQuery] SomethingRequest request)
{
    // ...
}

With SomethingRequest looking something like this:

public class SomethingRequest
{
    public int? Limit { get; set; }

    public int Page { get; set; } = 1;

    public string OrderBy { get; set; }

    public boolean? Ascending { get; set; };
}

The method in my Axios Typescript output looks something like this:

getSomething(id: number, limit?: number | null | undefined, page?: number | undefined, orderBy?: string | null | undefined, ascending?: boolean | undefined , cancelToken?: CancelToken | undefined): Promise<PagedResultOfSomethingDto> {

Meaning if I want to make a request specifying the order but nothing else I have to do:

client.getSomething(1, null, null, "Name")

If I was using axios directly I could do this:

axios.get(`api/controller/${id}/something`, { params: { orderBy: "Name" } })

What I would like is the option for NSwag to generate client methods within optional parameters in an object or interface so you get something like this:

getSomething(id: number, params?: { limit?: number | null | undefined, page?: number | undefined, orderBy?: string | null | undefined, ascending?: boolean | undefined , cancelToken?: CancelToken | undefined }): Promise<PagedResultOfSomethingDto> {

And you can call it like this:

client.getSomething(1, { orderBy: "Name" })

As well as being cleaner this protects you from bugs caused by the order of parameters changing.

I would be tempted to write my own templates to solve this but I cannot find any documentation on how to do this, and how to configure nswag to reference them.

RicoSuter commented 3 years ago

See https://github.com/RicoSuter/NSwag/wiki/Templates but i'm not sure whether the templating is powerful enough to implement that purely in liquid... in general it would be nice to have this as another option in the ts generator

terrencejames commented 2 years ago

Any updates on this?