I've a collection of Item objects. From a REST API (using Node.js and Nest.js), I'm returning many objects and a count of all available objects in the database:
type Response = {
many: Item[];
count: number;
}
I'm also using Swagger and a TypeScript codebase (I'm using Nest.js and its Swagger plugin).
Here, instead of using the Response type, I want to specify a class definition as a returned type on my API controller (: Promise<GetManyItemsAndCountDto>), so the API response is automatically documented in the Swagger schema:
export class GetManyItemsAndCountDto extends GetManyAndCountType(Item) {}
export class ItemsController {
async getItems(/* ... */): Promise<GetManyItemsAndCountDto> {
// ...
}
}
Like here, in my project all APIs returning a collection of objects, are also returning a count.
How I can define correctly a generic and reusable GetManyAndCountType() class/function to get the response definition correctly documented with Swagger?
What I've tried:
- I tried the solution below using a mixin (inspired by another use case). The
GetManyItemsAndCountDtois well created in the swagger json schema, but only as an "object" without its 2 properties:many: Items[]andcount: number, which is useless.
interface IGetManyAndCount<T> {
many: T[];
count: number;
}
export function GetManyAndCountType<T>(ResourceClass) {
return class GetManyAndCount implements IGetManyAndCount<T> {
many: typeof ResourceClass[];
count: number;
};
}
export class GetManyItemsAndCountDto extends GetManyAndCountType(Items) {}
- For the time being, the only working solution I have is to create explicitly a class
GetManyItemsAndCountDto(but I would like to find a more generic solution to avoid code duplication on several similar situations and APIs I have):
export class GetManyItemsAndCountDto {
many: Item[];
count: number;
}
Thanks in advance for any help or comments.