Home > Net >  Serialize async response from a database client
Serialize async response from a database client

Time:09-03

I have an endpoint which is used to create an item. The controller calls the service which creates the item, makes some changes on the db and db returns data based on the procedure. The db returns a json like response, but is not always the same, so I have to adjust on the backend so that I can formalize the response type.

The problem is that create item service is asynchronous and I need to be able to await the response so I can make a new response based on that. How can I await the response and that I get from db client and then return data based on that.

This is my Action and I want to be able to serialize async response from service

[HttpPost]
public IActionResult CreateItem([FromBody] InputModel item)
{
  var jsonString = _itemService.CreateItem(item);
  ResponseModel? response = JsonSerializer.Deserialize<ResponseModel>(jsonString);
  return new ObjectResult(response.Response) { StatusCode = response.StatusCode };
}

The default response model

public class ResponseModel
{
    public string Response { get; set; }
    public int StatusCode { get; set; }
}

Create Item service, which makes the post request to the client and it has to be async. Depending on the status code that is coming from the client, I want to be able to set my action status code as well.

public async Task<string> CreateItem(InputModel item)
{
  if (item.VersionType != 1)
  {
    return new { Response = "Incorrect data", StatusCode = 400 }.ToString()!;
  }
  var json = JsonSerializer.Serialize(item);
  var data = new StringContent(json, Encoding.UTF8, "application/json");
  var response = await client.PostAsync(url, data);
  var content = await response.Content.ReadAsStringAsync();
  return content;
}

CodePudding user response:

You can make your action method async and then await the method call _itemService.CreateItem for it :

[HttpPost]
public async Task<IActionResult> CreateItem([FromBody] InputModel item)
{
  var jsonString = await _itemService.CreateItem(item);
  ResponseModel? response = JsonSerializer.Deserialize<ResponseModel>(jsonString);
  return new ObjectResult(response.Response) { StatusCode = response.StatusCode };
}

Now your action method would asyncrounously wait for the result from CreateItem and when it returs result, it will continue executing further and send the deserialized response back to client.

  • Related