I'm trying to implement a generic CRUD interface for my API in Typescript using Axios.
Suppose the API exposes endpoints for doing CRUD operations with 2 entities. Say the endpoints are /users and /posts/ and both take URL parameters offset and count (for pagination). Example of responses:
GET /users?offset=2&count=2
{
"users": ["user1", "user2"],
"total": 4 // the total number of users that exist
}
and similarly for posts instead the key for the array of posts is `"posts".
I tried to create a generic function to get either of users/posts as follows:
export const getPage =
async <T extends Persistable>(offset: number, count: number): Promise<PaginatedResponse<T>> => {
const response = await axios.get<PaginatedResponse<T>>(
`${SOME_URL}/<BLANK>`,
{
params: { page, size },
transformResponse: [
(data) => ({
...data,
items: data[<BLANK>],
})
]
},
);
return response.data;
};
Where Persistable interface that both User and Post interfaces inherit from and PaginatedResponse interface looks as follows:
export interface PaginatedResponse<T> {
readonly total: number;
readonly items: T[];
}
Basically, I'd need to fill in the <BLANK>s by e.g. somehow getting strings "users"/"posts" respectively based on the passed type T.
Can anyone think of a way to achieve this, please?
nameproperty of the constructor. Other options might be just setting a property yourself with the value or doing some structural comparison of the object to determine its type.