ABP 集成 nswag 根據 Swagger API 自動生成操作類代碼

記錄日期: 2019-9-22 23:12:39

原文鏈接:https://www.cnblogs.com/Qbit/p/11569906.html

 

集成記錄:

 

npm install nswag --save-dev

 

複製  NSwag\src\NSwag.CodeGeneration.TypeScript\Templates 目錄下的所有文件到 ts 項目的 nswag 目錄下,nswag 源碼下載困難,人肉拷貝吧 https://github.com/RicoSuter/NSwag/tree/master/src/NSwag.CodeGeneration.TypeScript/Templates

修改 service.config.nswag 中的 templateDirectory 爲: "templateDirectory": "./Templates",

至此,可以隨意調整複製過來的 liquid 模板,比如增加clientBaseClass 的引用  我的 完整配置如下:

{
  "runtime": "Default",
  "defaultVariables": null,
  "documentGenerator": {
    "fromDocument": {
      "json": "",
      "url": "http://localhost:21021/swagger/v1/swagger.json",
      "output": null
    }
  },
  "codeGenerators": {
    "openApiToTypeScriptClient": {
      "className": "{controller}ServiceProxy",
      "moduleName": "",
      "namespace": "",
      "typeScriptVersion": 2.7,
      "template": "Axios",
      "promiseType": "Promise",
      "httpClass": "HttpClient",
      "useSingletonProvider": false,
      "injectionTokenType": "InjectionToken",
      "rxJsVersion": 6.0,
      "dateTimeType": "Date",
      "nullValue": "Null",
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "generateOptionalParameters": false,
      "exportTypes": true,
      "wrapDtoExceptions": false,
      "exceptionClass": "ApiException",
      "clientBaseClass": "AbpServiceBase",
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "protectedMethods": [],
      "configurationClass": null,
      "useTransformOptionsMethod": false,
      "useTransformResultMethod": true,
      "generateDtoTypes": true,
      "operationGenerationMode": "MultipleClientsFromPathSegments",
      "markOptionalProperties": false,
      "generateCloneMethod": false,
      "typeStyle": "Class",
      "classTypes": [],
      "extendedClasses": [],
      "extensionCode": "",
      "generateDefaultValues": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": true,
      "generateConstructorInterface": false,
      "convertConstructorInterfaceData": true,
      "importRequiredTypes": true,
      "useGetBaseUrlMethod": false,
      "baseUrlTokenName": "API_BASE_URL",
      "queryNullValue": "",
      "inlineNamedDictionaries": false,
      "inlineNamedAny": false,
      "templateDirectory": "./Templates",
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "../src/api/abp-service-proxies.ts"
    }
  }
}

 

ABP 的swagger 必須使用這種方式獲取data.result

修改 Client.ProcessResponse.ReadBodyStart.liquid 

{% elseif Framework.IsAxios -%}
const _responseText = response.data.result;    
 
或者你不去修改模板,使用 我的配置,然後繼承這個類,去除註釋代碼
 
import { AxiosResponse } from "axios";

export class AbpServiceBase {

    protected transformResult(url: string, response: AxiosResponse, processor: (response: AxiosResponse) => Promise<any>): Promise<any> {
        // if(response.data.result){ 
        //     response.data=response.data.result;
        // }
        console.log(response) 
        return processor(response);
    }
}

  

修改 File.liquid 文件,在48行增加 :

import { AbpServiceBase } from './abp-service-base';
 
在項目的 packge.json scripts 中增加:
  "genApi":"cd nswag &.\\refresh.bat"
 
這樣可以不用每次輸入代碼執行生成
 

 

 

 
 
調試記錄: 特麼的。。跑不起來依賴版本要全部安裝或者改別嘗試了,後續直接人肉跟蹤吧,跳過此節

NSwag 中大量使用 啓動新進程的方式調用代碼,調試起來比較麻煩,在此記錄

斷點位置:NSwag.Commands.dll!NSwag.Commands.NSwagDocument.ExecuteCommandLineAsync.AnonymousMethod__0() 行 128
在 C:\projects\nswag\src\NSwag.Commands\NSwagDocument.cs(128)

本機已安裝 nswagStuido 
斷點位置啓動進程信息:
路徑:"C:\\Program Files (x86)\\Rico Suter\\NSwagStudio\\Win/nswag.exe"
GetArgumentsPrefix()  輸出  “”
 
斷點信息:

> NSwag.Commands.dll!NSwag.Commands.NSwagDocument.StartCommandLineProcessAsync(string command) 行 258 C#

參數:run "C:\Users\hyzx8\AppData\Local\Temp\nswag_document_1a466f99-7edb-4012-9450-30e5bc3d7133_config.json"
執行後輸出 結果
 
 
使用 LSpy 打開:"C:\\Program Files (x86)\\Rico Suter\\NSwagStudio\\Win/nswag.exe
找到main 函數
	Console.Write("NSwag command line tool for .NET 4.6.1+ " + RuntimeUtilities.CurrentRuntime + ", ");
	return new NSwagCommandProcessor(new ConsoleHost()).Process(args);

 回到源代碼,搜索:NSwag command line tool for .NET 4.6.1+

打開 NSwag.Console 項目,跟蹤到 NSwagCommandProcessor  類的 Process(string[] args) 方法

跟蹤到:OpenApiToCSharpControllerCommand.RunAsync()  加上斷點

 

 

 

進入 C:\Program Files (x86)\Rico Suter\NSwagStudio\Win  

Shift 右鍵打開powershell  輸入 .\NSwag.exe run "C:\Users\hyzx8\source\repos\hyzx86\vue-typescript-admin-template\nswag\service.config.nswag"

 

先不要執行,此時使用vs附加到該 Powershell 的進程

 

 

 

 

 
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章