Swagger-client - Recommended usage/creation of SwaggerClient
Hi all.
I'm completely new to using Swagger, and I'm trying to refactor our React project to use our Swagger schema-generated Spring Boot API. I want to create the SwaggerClient once inside a file (so I don't need to repeat the creation of the SwaggerClient every time with the schema URL) with custom hooks then use async/await to fetch and return the result. Is this an "acceptable" approach or against Swagger's intentions in any way? Resources seem to be very thin on the swagger-client front when I've searched via Google.
Something like the following:
// DataHooks.js
const SWAGGER_CLIENT = new SwaggerClient("/path/to/api.json").client;
export function useSwaggerApi() {
return SWAGGER_CLIENT.apis;
}
export async function useAddFood() {
const [food, setFood] = useState(null);
const FOOD_API = useSwaggerApi().food;
try {
const response = await FOOD_API.addFoodItem({ requestBody: { ... }});
setFood(response);
} catch (error {}
return food;
}
I've logged out the above in a dummy component with the example pets.json to make sure the SwaggerClient resolves and I can see the pets, store etc so it seems to work as expected.
Thanks all. I really appreciate your help. 🙂
Depending on how you need to use SwaggerClient, you may not need to instantiate a new instance of SwaggerClient. Instead, you can import SwaggerClient, then directly access SwaggerClient methods. You can find some examples here: https://github.com/swagger-api/swagger-js/tree/master/docs/usage