'How to remove the redundant part of the Model property returned by the api

Describe:

  1. What I want to do:

    I used KubernetesClient library to get the information in K8s, now I want to get some information in Node like Node name etc.

  2. My method:

    I used V1NodeList Model and ListNodeAsync interface to get information

  3. My question:

    But they are returning too much data, I just want to get the data I want and get rid of the extra properties, what should I do?

    Also in the GetKubernetesNodeAsync method, how can I return the value, I think return (T)(object)models; is not a good way.

    This is a .net question.

Code:

  1. Controller
    [HttpGet("Nodes")]
    public async Task<ActionResult<V1NodeList>> GetNodeAsync()
    {
        var nodes = await _resourceAccess.GetKubernetesNodeAsync(default);
       
        return nodes;
    }
  1. Method
    public async Task<T> GetKubernetesNodeAsync(CancellationToken cancellationToken = default)
    {
        // todo Temp
        var config = new KubernetesClientConfiguration { Host = "http://127.0.0.1:8001" };
       
        var client = new Kubernetes(config);
       
        var models = await client.CoreV1.ListNodeAsync(cancellationToken: cancellationToken);
       
        return (T)(object)models;
    }
  1. Data returned

Below is the current data returned



Solution 1:[1]

In this case, you can create a model of your own that you return from your controller. This is a class that only contains the properties that you want, e.g.

public class NodeInfo 
{
  public string Name { get; set; }
  public DateTime? Creation { get; set; }
}

In your controller (or your ressource access method), you map to this model class, e.g.

[HttpGet("Nodes")]
public async Task<ActionResult<IEnumerable<NodeInfo>>> GetNodeAsync()
{
    var nodes = await _resourceAccess.GetKubernetesNodeAsync(default);
   
    return nodes.Items.Select(x => new NodeInfo() {
      Name = x.Name, 
      Creation = x.CreationTimestamp,
    });
}

An additional plus of this approach is that your API does not necessarily have to be changed if the underlying KubernetesClient models change as long as you can map the new interface to your model.

If you have many places in code where you need to map to other data formats, you should have a look at the AutoMapper library. This automates the mapping process.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Markus