从 Swagger 生成静态 Javascript 客户端以用于 React Native

Generate static Javascript client from Swagger for use in React Native

我正在构建一个 React Native 应用程序,它将使用 API 和 Swagger 2.0 定义。我在 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.

访问了 Swagger 的仓库

问题是生成器是动态的,因为我会将客户端嵌入到移动应用程序中,动态生成器不是一个选项。他们还说 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 有第三方项目可用。 (虽然该第 3 方生成器有效,但我不想使用可能随时损坏的已弃用工具,因为我将在新端点到达时更新 API 客户端。而且该工具也不会真正生成正如它在自己的回购协议中所说的那样,无论如何都是好的代码。)

此时我卡住了。从 Swagger 定义生成用于 React Native 的静态 Javascript 客户端的受支持方式是什么?

您可以使用Swagger Codegen生成javascript客户端sdk。但是,其中使用的 javascript 代码不适用于 React Native 的 fetch 实现。为了克服这个问题,您可以简单地扩展 ApiClient 的实现以使用 React Native 获取,例如:

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
      });
  }
}

稍后在您的其他方法中使用它,例如

class CustomUsersApi extends UsersApi {

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

关于这方面的详细实现,可以参考博客posthttps://medium.com/@lupugabriel/using-swagger-codegen-with-reactnative-4493d98cac15