iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
Software Development

全端工程師團隊的養成計畫系列 第 12

Day12 Backend API 彙整資料並回傳至前端

  • 分享至 

  • xImage
  •  

Backend API 已經可以接收前端的呼叫需求,HR API Service 取得人事資料的部分也完成了。接下來要透過 Backend API 進行整合,並匯整成前端所需的物件格式,讓前端能讀取並呈現在介面中。本篇我們持續完成下圖黃色區塊。
圖12-1
圖12-1:後端在取得身份後,讀取人事資料,並完成資料整理,回應至前端站台。

1. 建立 Interface 層

  • 於 Backend API 專案建立檔案 IHRApi.cs,建立 Interface 層
namespace Core.Interface
{
    public interface IHRApiClient
    {
        Task<Employee> GetEmployeeByEmailOrEmplidAsync(string email, string emplid);
    }
}

2. 實作取得人事資料 Service

  • 新增 HRApi.cs 檔案實作 GetEmployeeByEmailOrEmplidAsync 內容
  • SendRequestAsync 為另外開發用來呼叫 API 的 helper,可透過 Swagger 與 NSwag 工具自動產生。
public virtual System.Threading.Tasks.Task<Employee> GetEmployeeByEmailOrEmplidAsync(string email, string emplid)
        {
            return GetEmployeeByEmailOrEmplidAsync(email, emplid, System.Threading.CancellationToken.None);
        }
       
        public virtual async System.Threading.Tasks.Task<Employee> GetEmployeeByEmailOrEmplidAsync(string email, string emplid, System.Threading.CancellationToken cancellationToken)
        {
            var queryParams = new Dictionary<string, string>
            {
                { "email", email },
                { "emplid", emplid }
            };
            var url = BuildUrl("/Employee", queryParams);
            return await SendRequestAsync<Employee>(HttpMethod.Get, url, null, cancellationToken);
        }

3. 新增整合回傳的資料 Data Transfer Object (Dto)

  • 新增 UserInfoDto.cs 整合回傳的資料 Data Transfer Object(Dto)給前端使用。
namespace Core.Models.Dto
{
    public class UserInfoDto
    {
        public required string id{ get; set; }
        public required string username { get; set; }
        public required string EmailAddress { get; set; }
        public string? deptName { get; set; }
        public string? deptId { get; set; }
        public string? deptName { get; set; }
        public string? compName { get; set; }
        public string? email { get; set; }
    }

}

4. 新增 UserInfoService.cs

  • 注入 IHRApiClient 的服務,透過調用 IHRApiClient.GetEmployeeByEmailOrEmplidAsync 取得人事資料
  • 整理回應後的 Data 轉置為 UserInfoDto 後回應物件載體。
namespace backendAPI.Services
{
   public class UserInfoService
   {
       private readonly IHRApiClient _apiHRClient;
       public UserInfoService(IHRApiClient apiHRClient )
        {
            _apiHRClient = apiHRClient;
        }
   }
   public async Task<UserInfoDto?> GetUserInfobyEmail(string email)
   {
       //呼叫 apiClient.GetEmployeeByEmailOrEmplidAsync 取得使用者資訊
       var employee = await _apiHRClient.GetEmployeeByEmailOrEmplidAsync(email, null);
       if (employee == null)
         {
                return null;
         }  
         //將取得的使用者資訊轉換成 UserInfoDto
         UserInfoDto userInfo = new UserInfoDto
          {
             id= employee.id,
             username= employee.Name,
             email= employee.Email,
             deptName = employee.DeptName,
             deptId = employee.DeptId,
             deptName= employee.DeptName,
             compName = employee.DeptLongName.Split('/')[0] ,
            };
            return userInfo;
         }
    }

}

5.新增 Controller API

  • 回到 BackendAPI Controller 注入 _userInfoService 服務,並將步驟 5 完成的 GetUserInfobyEmail 加入使用,做為回應
namespace backendAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserInfoController : ControllerBase
    {
        private readonly UserInfoService _userInfoService;

        // 建構子注入 UserInfoService
        public UserInfoController(UserInfoService userInfoService)
        {
            _userInfoService = userInfoService;
        }

        [HttpGet]
        [ProducesResponseType(typeof(UserInfoDto), 200)]
        public async Task<IActionResult> GetLoginUserInfo()
        {
            var emailClaim = User.FindFirst(ClaimTypes.Upn)?.Value;
            UserInfoDto? userInfo = await _userInfoService.GetUserInfobyEmail(emailClaim);
            if (userInfo == null)
            {
                return NotFound();
            }
            return Ok(userInfo);
        }
    }
}


驗證成果

啟動以下服務,前端在發送 Request 時,會對接到 Backend API,並在從 HR API 取得資料後進行匯整,再回應至前端。

  • 前端站台
  • BackendAPI
  • HRAPI
    圖12-2:前端登入後向後端發出請求成功
    圖12-2

圖12-3:檢視回應,確認有得到資料
圖12-3


Ending Remark

步驟概覽

  • 在 Backend API 建立 Interface 與 IHRService,呼叫 HR API Service
  • 前端傳入使用者 Email 作為參數,透過 IHRService 呼叫 HR API 並取得回應
  • 將 HR API 回應整理為 UserInfoDto,透過 Controller 回傳前端

主要程式檔案與內容

  • IHRApi.cs:定義 IHRApiClient 介面
  • HRApi.cs:Service 實作 GetEmployeeByEmailOrEmplidAsync,使用 SendRequestAsync 呼叫 API
  • UserInfoDto.cs:整合回傳資料,提供給前端
  • UserInfoService.cs:注入 IHRApiClient,整理 HR API 回傳資料並生成 DTO
  • UserInfoController:注入 UserInfoService,透過 GetLoginUserInfo API 回應前端

今日完成了後端與人事資料的互動,開始在往前端將取得的資料於前端顯示~明天見


上一篇
Day11 整合人事資料
下一篇
Day13 前端收到資料了,可以顯示於介面上囉
系列文
全端工程師團隊的養成計畫13
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言