Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate static Javascript client from Swagger for use in React Native

I'm building a React Native app that will consume an API with Swagger 2.0 definition. I went to Swagger's repo at https://github.com/swagger-api/swagger-codegen#where-is-javascript and it points to their Javascript generator at https://github.com/swagger-api/swagger-js.

The problem is that the generator is dynamic, and since I'll be embedding the client in a mobile app, dynamic generator is not an option. They also say that there's a third party project available at https://github.com/wcandillon/swagger-js-codegen, which says that the project is no longer maintained and points back to https://github.com/swagger-api/swagger-codegen. (while that 3rd party generator works, I don't want to use a deprecated tool that might break any time since I'll be updating the API client when new endpoints arrive. And that tool also doesn't generate really good code anyway as it says in its own repo.)

At this point I'm stuck. What is the supported way of generating a static Javascript client from Swagger definition for use in React Native?

like image 852
Can Poyrazoğlu Avatar asked Apr 02 '19 19:04

Can Poyrazoğlu


1 Answers

You can use Swagger Codegen to generate a javascript client sdk. However, the javascript code used in it will not work with React Native's fetch implementation. To overcome that, you can simply extend the implementation of ApiClient to use the React Native fetch like:

class CustomApiClient extends ApiClient {


 callApi(path, httpMethod,   pathParams,queryParams,collectionQueryParams, headerParams, formParams, bodyParam,authNames, contentTypes, accepts,returnType, callback) {
    return fetch(`${this.basePath}${path}`,
      {
        method: httpMethod
      });
  }
}

Later using it in your other methods such as

class CustomUsersApi extends UsersApi {

 constructor() {
    super(new CustomApiClient());
  }
}

For a detailed implementation on this, you can refer the blog post https://medium.com/@lupugabriel/using-swagger-codegen-with-reactnative-4493d98cac15

like image 172
Dani Akash Avatar answered Nov 13 '22 05:11

Dani Akash