Node.js 學習筆記 — TypeScript AutoMapper 介紹 (二)

Tom
appxtech
4 min readMar 15, 2023

--

上一篇透過AutoMaper的基礎設定,來達到簡單的物件轉換,這篇將對 AutoMapper的幾個常用的 mapping configuration 做基礎應用介紹

首先先提供本篇Model的結構

forMember
forMember 能夠讓你對 destination 的屬性做的控制,讓你能夠客製你想要的 mapping 方式。

若我們想將Dto 中 UserInfo 變成 entity 的 userId + userName 的組合,只使用設定是沒辦法的,但使用 forMember 後就可以輕鬆達成。

這邊注意到,forMember 中使用的 mapFrom 會使 AutoMapper 根據傳入的 valueSelector 去 sourceObject 中取值進行 mapping。

另外,若有多個屬性需要forMember處理,直接加上就好囉!

* forMember除了 mapFrom,還有多種map的設定,可以到 官網 去參考。

typeConverters

typeConverters可以設定sourceObject 中特定型別的屬性對應到 destinationObject 的特定型別屬性時,自動做處理,這邊上例子。

UserInfo.entity 中有兩個 型別為 Date 的屬性 : birthDay、registrationDate
對應到 UserInfo.dto 中的 birthDay、registrationDate 為 String 型別
當你需要對其做格式處理時當然也可以用 forMember,但若 mapping 方式一樣,則可以簡化成一個 typeConverters 即可,下方例子。

namingConventions

namingConventions 設定能夠啟用 "Auto Flattening" 功能,意思就是能將多層物件結構"展平"成簡單的單層結構,而其運作原理就是透過屬性名稱的命名規則去解析。

Automapper 有提供三種命名規則的設定。

  • CamelCaseNamingConvention(駝峰)
  • PascalCaseNamingConvention (帕斯卡)
  • SnakeCaseNamingConvention (蛇形)

本篇使用駝峰介紹。

namingConventions 設定方式

接下來,若是我們只需要 map 使用者所在城市,不需要詳細地址,則 UserInfo.Dto 中的 address只需要將屬性名稱改為"addressCity",則AutoMapper就會依據駝峰命名規則將 "addressCity"解析為 "address"和"city"兩個名稱,並且 "address" 會對應到 UserInfo.entity to UserInfoDto 的 address 屬性 mapping ,city 則會對應到上一篇設定過的 Address to AddressDto 的 city 屬性 mapping 。

beforeMap、afterMap

顧名思義就是在mapping開始前、後會執行的部分,使用方式可以加在createMap 時,也可以加在mapper.map()呼叫時。

以 afterMap為例

  • 須注意,beforMap和afterMap在使用mapper.mapArray時是沒有用的,若需要使用 mapperArray,可以分別改用 preMap 和 postMap。

Summary

AutoMapper 有提供許多API,讓開發者能夠更細緻的去針對不同 class 之間的 mapping 來調整。

千萬不要覺得多加這個設定很麻煩,當開發時遇到很多次物件轉換時,就會感受到其強大之處,讓人愛不釋手。

最後再強調一次,最適合使用 AutoMapper 作轉換的 classes 之間需要兩個 classes 之間的轉換規則需固定,否則使用 AutoMapper 反而會造成開發上的困擾。

AutoMapper 的簡單介紹就到這邊~有更多的實戰功用就需要在開發中摸索啦~祝各位好運。

Reference

https://automapperts.netlify.app/docs/getting-started/overview

--

--

Tom
appxtech
Writer for

Major in Computer Science, Web Backend Engineer