From e359803d76e44dd71eb92f4b4db85cb1ed5a8449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E4=BA=91=E9=87=91YunjinXu?= Date: Fri, 13 Dec 2024 11:26:15 +0800 Subject: [PATCH] =?UTF-8?q?refactor(QueryPrepared):=20Add=20OrString?= =?UTF-8?q?=E3=80=81String2DtmError=E3=80=81Result2HttpJson=20methods=20to?= =?UTF-8?q?=20Utils.cs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add OrString、String2DtmError、Result2HttpJson methods to Utils.cs - Refactor sample controller Msg QueryPrepared, by invoking new methods in Utils.cs --- .../Controllers/MsgTestController.cs | 55 ++++-------------- src/Dtmcli/DtmImp/Utils.cs | 56 +++++++++++++++++++ tests/Dtmcli.Tests/UtilsTests.cs | 45 ++++++++++++++- 3 files changed, 110 insertions(+), 46 deletions(-) diff --git a/samples/DtmSample/Controllers/MsgTestController.cs b/samples/DtmSample/Controllers/MsgTestController.cs index d33011d..c34e689 100644 --- a/samples/DtmSample/Controllers/MsgTestController.cs +++ b/samples/DtmSample/Controllers/MsgTestController.cs @@ -1,5 +1,4 @@ using System; -using System.Net; using Dtmcli; using DtmMongoBarrier; using DtmSample.Dtos; @@ -239,8 +238,6 @@ public async Task MsgMongoQueryPrepared(CancellationToken cancell return Ok(new { dtm_result = res }); } - - /// /// MSG QueryPrepared(mssql) /// @@ -267,55 +264,23 @@ public async Task MsgMsSqlQueryPrepared(CancellationToken cancell { var bb = _factory.CreateBranchBarrier(Request.Query); _logger.LogInformation("bb {0}", bb); - + string ret; await using (SqlConnection conn = GetMssqlConn()) { ret = await bb.QueryPrepared(conn); } - - (int status, object res) = Result2HttpJson(ret); - return StatusCode(status, res); + + ret = Dtmcli.DtmImp.Utils.OrString(ret, DtmCommon.Constant.ResultSuccess); + Exception error = Dtmcli.DtmImp.Utils.String2DtmError(ret); + + return WrapHandler(error); } - - // ref go implement: dtmutil.WrapHandler -> dtmcli.Result2HttpJSON - // Result2HttpJSON return the http code and json result - // if result is error, the return proper code, else return StatusOK - // func Result2HttpJSON(result interface{}) (code int, res interface{}) { - // err, _ := result.(error) - // if err == nil { - // code = http.StatusOK - // res = result - // } else { - // res = map[string]string{ - // "error": err.Error(), - // } - // if errors.Is(err, ErrFailure) { - // code = http.StatusConflict - // } else if errors.Is(err, ErrOngoing) { - // code = http.StatusTooEarly - // } else if err != nil { - // code = http.StatusInternalServerError - // } - // } - // return - // } - private static (int httpStatusCode, object bodyObj) Result2HttpJson(string ret) - { - if (ret == string.Empty) - return ((int)HttpStatusCode.OK, ret); - var res = new { error = ret }; - switch (ret) - { - // Code 409 => ErrFailure; Code 425 => ErrOngoing; Code 500 => InternalServerError - case "FAILURE": - return ((int)HttpStatusCode.Conflict, res); - case "ONGOING": - return (425 /*HttpStatusCode.TooEarly*/, res); - default: - return ((int)HttpStatusCode.InternalServerError, res); - } + private IActionResult WrapHandler(Exception error) + { + (int status, object res) = Dtmcli.DtmImp.Utils.Result2HttpJson(error); + return StatusCode(status, res); } /// diff --git a/src/Dtmcli/DtmImp/Utils.cs b/src/Dtmcli/DtmImp/Utils.cs index e231ea4..0b374e9 100644 --- a/src/Dtmcli/DtmImp/Utils.cs +++ b/src/Dtmcli/DtmImp/Utils.cs @@ -39,5 +39,61 @@ public static void CheckStatus(HttpStatusCode status, string dtmResult) throw new DtmException(string.Format(CheckStatusMsgFormat, status.ToString(), dtmResult)); } } + + /// + /// OrString return the first not null or not empty string + /// + /// + /// + public static string OrString(params string[] ss) + { + foreach (var s in ss) + { + if (!string.IsNullOrEmpty(s)) + return s; + } + + return ""; + } + + /// + /// translate string to dtm error + /// + /// + /// + public static Exception String2DtmError(string str) + { + if (str == DtmCommon.Constant.ResultSuccess || str == string.Empty) + return null; + if (str == string.Empty) + return null; + if (str == DtmCommon.Constant.ResultFailure) + return new DtmCommon.DtmFailureException(); + if (str == DtmCommon.Constant.ResultOngoing) + return new DtmCommon.DtmOngingException(); + return new Exception(str); + } + + /// + /// translate object to http response + /// 409 => ErrFailure; Code 425 => ErrOngoing; Code 500 => InternalServerError + /// + /// + /// + public static (int httpStatusCode, object res) Result2HttpJson(object result) + { + if (result is not Exception err) + { + return ((int)(HttpStatusCode.OK), result); + } + + var res = new { error = err.Message }; + if (err is DtmFailureException) + return ((int)HttpStatusCode.Conflict, res); + if (err is DtmOngingException) + return (425 /*HttpStatusCode.TooEarly*/, res); + + return ((int)HttpStatusCode.InternalServerError, res); + } } } diff --git a/tests/Dtmcli.Tests/UtilsTests.cs b/tests/Dtmcli.Tests/UtilsTests.cs index 546d450..282241f 100644 --- a/tests/Dtmcli.Tests/UtilsTests.cs +++ b/tests/Dtmcli.Tests/UtilsTests.cs @@ -1,6 +1,10 @@ -using Xunit; +using System; +using Xunit; using System.Net; using System.Net.Http; +using System.Text.Json.Serialization; +using DtmCommon; +using Newtonsoft.Json; namespace Dtmcli.Tests { @@ -62,5 +66,44 @@ public void CheckStatus_Should_Throw_Failure_Exception(HttpStatusCode code, stri { Assert.Throws(() => DtmImp.Utils.CheckStatus(code, msg)); } + + [Fact] + public void OrString() + { + Assert.Equal("", DtmImp.Utils.OrString()); + Assert.Equal("A", DtmImp.Utils.OrString("", "A")); + Assert.Equal("A", DtmImp.Utils.OrString("", "A", "B")); + Assert.Equal("A", DtmImp.Utils.OrString("A", "B")); + } + + [Fact] + public void String2DtmError() + { + Assert.IsType(DtmImp.Utils.String2DtmError(null)); + Assert.Null(DtmImp.Utils.String2DtmError(string.Empty)); + Assert.Null(DtmImp.Utils.String2DtmError("SUCCESS")); + Assert.IsType(DtmImp.Utils.String2DtmError("FAILURE")); + Assert.IsType(DtmImp.Utils.String2DtmError("ONGOING")); + Assert.IsType(DtmImp.Utils.String2DtmError("Object ...")); + } + + [Fact] + public void Result2HttpJson() + { + Assert.Equal(200, DtmImp.Utils.Result2HttpJson(null).httpStatusCode); + Assert.Equal(409, DtmImp.Utils.Result2HttpJson(new DtmFailureException()).httpStatusCode); + Assert.Equal(425, DtmImp.Utils.Result2HttpJson(new DtmOngingException()).httpStatusCode); + Assert.Equal(500, DtmImp.Utils.Result2HttpJson(new DtmDuplicatedException()).httpStatusCode); + + Assert.Equal(500, DtmImp.Utils.Result2HttpJson(new Exception("message context A")).httpStatusCode); + Assert.Contains("message context A", JsonConvert.SerializeObject(DtmImp.Utils.Result2HttpJson(new Exception("message context A")).res)); + + Assert.Equal(200, DtmImp.Utils.Result2HttpJson("normal text").httpStatusCode); + Assert.Equal("normal text", DtmImp.Utils.Result2HttpJson("normal text").res); + + var obj = new { A = "hello", B = "world" }; + Assert.Equal(200, DtmImp.Utils.Result2HttpJson(obj).httpStatusCode); + Assert.Equal(obj, DtmImp.Utils.Result2HttpJson(obj).res); + } } } \ No newline at end of file