Skip to content

Commit

Permalink
refactor(QueryPrepared): Add OrString、String2DtmError、Result2HttpJson…
Browse files Browse the repository at this point in the history
… methods to Utils.cs

- Add OrString、String2DtmError、Result2HttpJson methods to Utils.cs
- Refactor sample controller Msg QueryPrepared, by invoking new methods in Utils.cs
  • Loading branch information
wooln committed Dec 13, 2024
1 parent 2179070 commit e359803
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 46 deletions.
55 changes: 10 additions & 45 deletions samples/DtmSample/Controllers/MsgTestController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Net;
using Dtmcli;
using DtmMongoBarrier;
using DtmSample.Dtos;
Expand Down Expand Up @@ -239,8 +238,6 @@ public async Task<IActionResult> MsgMongoQueryPrepared(CancellationToken cancell
return Ok(new { dtm_result = res });
}



/// <summary>
/// MSG QueryPrepared(mssql)
///
Expand All @@ -267,55 +264,23 @@ public async Task<IActionResult> 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);
}

/// <summary>
Expand Down
56 changes: 56 additions & 0 deletions src/Dtmcli/DtmImp/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,61 @@ public static void CheckStatus(HttpStatusCode status, string dtmResult)
throw new DtmException(string.Format(CheckStatusMsgFormat, status.ToString(), dtmResult));
}
}

/// <summary>
/// OrString return the first not null or not empty string
/// </summary>
/// <param name="ss"></param>
/// <returns></returns>
public static string OrString(params string[] ss)
{
foreach (var s in ss)
{
if (!string.IsNullOrEmpty(s))
return s;
}

return "";
}

/// <summary>
/// translate string to dtm error
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Exception String2DtmError(string str)
{
if (str == DtmCommon.Constant.ResultSuccess || str == string.Empty)
return null;
if (str == string.Empty)
return null;

Check warning on line 69 in src/Dtmcli/DtmImp/Utils.cs

View check run for this annotation

Codecov / codecov/patch

src/Dtmcli/DtmImp/Utils.cs#L69

Added line #L69 was not covered by tests
if (str == DtmCommon.Constant.ResultFailure)
return new DtmCommon.DtmFailureException();
if (str == DtmCommon.Constant.ResultOngoing)
return new DtmCommon.DtmOngingException();
return new Exception(str);
}

/// <summary>
/// translate object to http response
/// 409 => ErrFailure; Code 425 => ErrOngoing; Code 500 => InternalServerError
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
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);
}
}
}
45 changes: 44 additions & 1 deletion tests/Dtmcli.Tests/UtilsTests.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down Expand Up @@ -62,5 +66,44 @@ public void CheckStatus_Should_Throw_Failure_Exception(HttpStatusCode code, stri
{
Assert.Throws<DtmCommon.DtmException>(() => 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<Exception>(DtmImp.Utils.String2DtmError(null));
Assert.Null(DtmImp.Utils.String2DtmError(string.Empty));
Assert.Null(DtmImp.Utils.String2DtmError("SUCCESS"));
Assert.IsType<DtmFailureException>(DtmImp.Utils.String2DtmError("FAILURE"));
Assert.IsType<DtmOngingException>(DtmImp.Utils.String2DtmError("ONGOING"));
Assert.IsType<Exception>(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);
}
}
}

0 comments on commit e359803

Please sign in to comment.