I have meticulously added type annotations to all endpoints in my API using the openapi-typescript package.
Now, I am looking to apply these annotations to my Axios requests as well. Here is a snippet of code from a Vue.js project I have been developing:
type FactRepeater = components['schemas']['FactRepeater'];
type FactRepeaterResponse =
paths['/api/v1/repeaters/fact-repeater/']['get']['responses']['200']['content']['application/json'];
type FactRepeaterRequest =
paths['/api/v1/repeaters/fact-repeater/']['get']['parameters']['query'];
const repeaters: Ref<Array<FactRepeater>> = ref([]);
async function requestRepeaters(
limit: number,
offset: number,
ordering: string | null = null,
): Promise<void> {
try {
const response: AxiosResponse<FactRepeaterResponse, FactRepeaterRequest> =
await api.get('/api/v1/repeaters/fact-repeater/', {
params: { limit, offset, ordering },
});
// These fields aren't null because this only happens on success
repeaters.value = response.data.results!;
pagination.value.rowsNumber = response.data.count!;
} catch (error) {
console.error(error);
}
}
The relevant sections of the components
schema are shown below:
// ...
// components["schemas"]
FactRepeater: {
id: number;
// ...
};
// ...
PaginatedFactRepeaterList: {
count?: number;
next?: string | null;
previous?: string | null;
results?: components["schemas"]["FactRepeater"][];
};
// ...
// paths['/api/v1/repeaters/fact-repeater/']['get']
responses: {
200: {
content: {
"application/json": components["schemas"]["PaginatedFactRepeaterList"];
};
};
};
parameters: {
query?: {
ordering?: string;
limit?: number;
offset?: number;
// ...
};
};
// ...
However, upon inspecting the code further, I realized that the descriptions of types could be improved. For instance, when I hover over params
in my IDE, it does not provide the expected information based on the filled-in AxiosResponse
.
https://i.sstatic.net/AxLLZ.png
This issue made me reconsider how the request type should be properly written for the AxiosResponse
. What modifications do I need to make?
As a follow-up question: How should the request type be defined in situations where an endpoint has no configurable request parameters, but only the endpoint itself?