เพื่อสาธิตแนวทางปฏิบัติของการ serialize และ deserialize domain object ไปเป็น JSON และกลับมา ลองมาสร้างตัวอย่างเล็กๆ กัน สมมติว่าเราต้องการ persist domain type Person ที่นิยามไว้แบบนี้:
| | module Domain = // our domain-driven types |
| | |
| | /// constrained to be not null and at most 50 chars |
| | type String50 = String50 of string |
| | |
| | /// constrained to be bigger than 1/1/1900 and less than today's date |
| | type Birthdate = Birthdate of DateTime |
| | |
| | /// Domain type |
| | type Person = { |
| | First: String50 |
| | Last: String50 |
| | Birthdate : Birthdate |
| | } |
type String50 และ Birthdate ไม่สามารถ serialize ได้โดยตรง ดังนั้นก่อนอื่นเราจะสร้าง DTO type ที่สอดคล้องกันชื่อ Dto.Person (เป็น Person ใน module Dto ) ซึ่งทุก field เป็น primitive ทั้งหมด แบบนี้:
| | /// A module to group all the DTO-related |
| | /// types and functions. |
| | module Dto = |
| | |
| | type Person = { |
| | First: string |
| | Last: string |
| | Birthdate : DateTime |
| | } |
ต่อไป เราต้องการ function “toDomain” และ “fromDomain” function เหล่านี้ผูกอยู่กับ DTO type ไม่ใช่ domain type เพราะ domain ไม่ควรรู้จัก DTO เลย ดังนั้นเราจะใส่ function เหล่านี้ไว้ใน module Dto ภายใต้ submodule ชื่อ Person ด้วยเช่นกัน
| | module Dto = |
| | |
| | module Person = |
| | let fromDomain (person:Domain.Person) :Dto.Person = |
| | ... |
| | |
| | let toDomain (dto:Dto.Person) :Result<Domain.Person, string > = |
| | ... |
![]() | ดังที่ได้กล่าวไปก่อนหน้านี้ เราจำเป็นต้องใช้ attribute CompilationRepresentation ใน F# เวอร์ชันก่อน 4.1 เมื่อ module มีชื่อเดียวกับ type |
รูปแบบการมี function คู่ fromDomain และ toDomain นี้เป็นสิ่งที่เราจะใช้อย่างสม่ำเสมอตลอดทั้งเล่ม
เริ่มต้นด้วย function fromDomain ที่แปลง domain type ให้เป็น DTO function นี้จะสำเร็จเสมอ ( Result ไม่จำเป็น) เพราะ domain type ที่ซับซ้อนสามารถแปลงเป็น DTO ได้เสมอโดยไม่มี error
| | let fromDomain (person:Domain.Person) :Dto.Person = |
| | // get the primitive values from the domain object |
| | let first = person.First |> String50.value |
| | let last = person.Last |> String50.value |
| | let birthdate = person.Birthdate |> Birthdate.value |
| | |
| | // combine the components to create the DTO |
| | {First = first; Last = last; Birthdate = birthdate} |
ในทิศทางตรงกันข้าม function toDomain จะแปลง DTO ให้กลายเป็น domain type และเนื่องจาก validation และ constraint ต่างๆ อาจล้มเหลวได้ toDomain จึงคืนค่าเป็น Result<Person,string> แทนที่จะเป็น Person ธรรมดาๆ
| | let toDomain (dto:Dto.Person) :Result<Domain.Person, string > = |
| | result { |
| | // get each (validated) simple type from the DTO as a success or failure |
| | let ! first = dto.First |> String50.create "First" |
| | let ! last = dto.Last |> String50.create "Last" |
| | let ! birthdate = dto.Birthdate |> Birthdate.create |
| | |
| | // combine the components to create the domain object |
| | return { |
| | First = first |
| | Last = last |
| | Birthdate = birthdate |
| | } |
| | } |
เราใช้ result computation expression เพื่อจัดการ flow ของ error เพราะ simple type อย่าง String50 และ Birthdate จะคืนค่าเป็น Result จาก method create ของมัน
ตัวอย่างเช่น เราอาจ implement String50.create โดยใช้แนวทางที่กล่าวถึงใน The Integrity of Simple Values code แสดงอยู่ด้านล่าง สังเกตว่าเรารวมชื่อ field เข้าไปเป็นพารามิเตอร์ด้วย เพื่อให้ได้ error message ที่เป็นประโยชน์:
| | let create fieldName str : Result<String50, string > = |
| | if String.IsNullOrEmpty(str) then |
| | Error (fieldName + " must be non-empty" ) |
| | elif str.Length > 50 then |
| | Error (fieldName + " must be less that 50 chars" ) |
| | else |
| | Ok (String50 str) |
Wrapping the JSON Serializer (การห่อหุ้ม JSON Serializer)
การ serialize JSON หรือ XML ไม่ใช่สิ่งที่เราอยากเขียน code เองตั้งแต่ต้น—เราคงอยากใช้ third-party library มากกว่า อย่างไรก็ตาม API ของ library นั้นอาจไม่เป็นมิตรกับสไตล์ functional เท่าไหร่ ดังนั้นเราอาจต้องการห่อหุ้ม (wrap) routine ของ serialization และ deserialization เพื่อให้เหมาะกับการใช้งานใน pipeline และแปลง exception ใดๆ ให้กลายเป็น Results นี่คือตัวอย่างวิธีห่อหุ้มส่วนหนึ่งของ standard .NET JSON serialization library ( Newtonsoft.Json ):
| | module Json = |
| | |
| | open Newtonsoft.Json |
| | |
| | let serialize obj = |
| | JsonConvert.SerializeObject obj |
| | |
| | let deserialize< ' a> str = |
| | try |
| | JsonConvert.DeserializeObject< ' a> str |
| | |> Result.Ok |
| | with |
| | // catch all exceptions and convert to Result |
| | | ex -> Result.Error ex |
เราสร้าง module Json ของเราเองเพื่อเก็บเวอร์ชันที่ปรับแต่งแล้วไว้ เพื่อให้เราสามารถเรียกใช้ function serialization อย่าง Json.serialize และ Json.deserialize ได้
A Complete Serialization Pipeline (Pipeline ของ Serialization แบบสมบูรณ์)
เมื่อมีตัวแปลง DTO-to-domain และ function serialization พร้อมแล้ว เราก็สามารถนำ domain type—นั่นคือ record Person —แปลงไปจนถึง JSON string ได้เลย:
| | /// Serialize a Person into a JSON string |
| | let jsonFromDomain (person:Domain.Person) = |
| | person |
| | |> Dto.Person.fromDomain |
| | |> Json.serialize |
ถ้าเราทดสอบดู เราจะได้ JSON string ตามที่คาดไว้:
| | // input to test with |
| | let person : Domain.Person = { |
| | First = String50 "Alex" |
| | Last = String50 "Adams" |
| | Birthdate = Birthdate (DateTime(1980,1,1)) |
| | } |
| | |
| | // use the serialization pipeline |
| | jsonFromDomain person |
| | |
| | // The output is |
| | // "{"First":"Alex","Last":"Adams","Birthdate":"1980-01-01T00:00:00"}" |
การประกอบ (compose) serialization pipeline นั้นตรงไปตรงมา เพราะทุก stage ไม่มี Result เข้ามาเกี่ยวข้องเลย แต่การประกอบ deserialization pipeline นั้นซับซ้อนกว่า เพราะทั้ง Json.deserialize และ PersonDto.fromDomain สามารถคืนค่าเป็น Results ได้ ทางแก้คือใช้ Result.mapError เพื่อแปลง failure ที่อาจเกิดขึ้นให้กลายเป็น choice type แบบเดียวกัน แล้วจากนั้นใช้ result expression เพื่อซ่อน error เหล่านั้นไว้ เหมือนกับที่เราได้เรียนรู้ใน Converting to a Common Error Type :
| | type DtoError = |
| | | ValidationError of string |
| | | DeserializationException of exn |
| | |
| | /// Deserialize a JSON string into a Person |
| | let jsonToDomain jsonString :Result<Domain.Person,DtoError> = |
| | result { |
| | let ! deserializedValue = |
| | jsonString |
| | |> Json.deserialize |
| | |> Result.mapError DeserializationException |
| | |
| | let ! domainValue = |
| | deserializedValue |
| | |> Dto.Person.toDomain |
| | |> Result.mapError ValidationError |
| | |
| | return domainValue |
| | } |
ลองทดสอบด้วย input ที่ไม่มี error กัน:
| | // JSON string to test with |
| | let jsonPerson = """{ |
| | " First ": " Alex ", |
| | " Last ": " Adams ", |
| | " Birthdate ": " 1980-01-01T00:00:00 " |
| | }""" |
| | |
| | // call the deserialization pipeline |
| | jsonToDomain jsonPerson |> printfn "%A" |
| | // The output is: |
| | // Ok {First = String50 "Alex"; |
| | // Last = String50 "Adams"; |
| | // Birthdate = Birthdate 01/01/1980 00:00:00;} |
เราจะเห็นได้ว่า Result โดยรวมคือ Ok และ domain object Person ถูกสร้างขึ้นสำเร็จแล้ว
ตอนนี้ลองปรับ JSON string ให้มี error—ชื่อว่างเปล่าและวันที่ไม่ถูกต้อง—แล้วรัน code อีกครั้ง:
| | let jsonPersonWithErrors = """{ |
| | " First ": "", |
| | " Last ": " Adams ", |
| | " Birthdate ": " 1776-01-01T00:00:00 " |
| | }""" |
| | |
| | // call the deserialization pipeline |
| | jsonToDomain jsonPersonWithErrors |> printfn "%A" |
| | |
| | // The output is: |
| | // Error (ValidationError [ |
| | // "First must be non-empty" |
| | // ]) |
จะเห็นว่าเราได้ case Error ของ Result จริงๆ พร้อมกับ error message ของ validation อันหนึ่ง ในแอปพลิเคชันจริง คุณอาจจะ log สิ่งนี้ไว้และอาจส่ง error กลับไปให้ผู้เรียกก็ได้ (ใน implementation นี้เราคืนค่าแค่ error แรกเท่านั้น หากต้องการคืนค่า error ทั้งหมด ดูได้ที่ Composing in Parallel with Applicatives .)
อีกแนวทางหนึ่งในการทำ error handling ระหว่าง deserialization คือไม่จัดการมันเลย แล้วปล่อยให้ code deserialization โยน exception ออกมาแทน ว่าจะเลือกแนวทางไหนก็ขึ้นอยู่กับว่าคุณอยากจัดการ error ของ deserialization ในฐานะสถานการณ์ที่คาดการณ์ไว้ หรือในฐานะ “panic” ที่ทำให้ pipeline ทั้งหมดพัง และนั่นก็ขึ้นอยู่กับว่า API ของคุณเปิดเผยต่อสาธารณะมากแค่ไหน คุณเชื่อใจผู้เรียกใช้มากแค่ไหน และคุณต้องการให้ข้อมูลเกี่ยวกับ error ประเภทนี้แก่ผู้เรียกใช้มากแค่ไหน
Working with Other Serializers (การทำงานกับ Serializer ตัวอื่นๆ)
code ด้านบนใช้ serializer ชื่อ Newtonsoft.Json คุณสามารถใช้ serializer ตัวอื่นได้ แต่อาจต้องเพิ่ม attribute ให้กับ type PersonDto ตัวอย่างเช่น การ serialize record type โดยใช้ DataContractSerializer (สำหรับ XML) หรือ DataContractJsonSerializer (สำหรับ JSON) คุณต้อง decorate DTO type ของคุณด้วย DataContractAttribute และ DataMemberAttribute :
| | module Dto = |
| | [<DataContract>] |
| | type Person = { |
| | [<field: DataMember>] |
| | First: string |
| | [<field: DataMember>] |
| | Last: string |
| | [<field: DataMember>] |
| | Birthdate : DateTime |
| | } |
สิ่งนี้แสดงให้เห็นข้อดีอีกอย่างของการแยก serialization type ออกจาก domain type—domain type จะไม่ถูกปนเปื้อนด้วย attribute ที่ซับซ้อนแบบนี้ เหมือนเช่นเคย การแยก concern ของ domain ออกจาก concern ของ infrastructure เป็นเรื่องดีเสมอ
อีก attribute หนึ่งที่ควรรู้จักเกี่ยวกับ serializer คือ CLIMutableAttribute ซึ่งจะสร้าง constructor แบบไม่มีพารามิเตอร์ (ที่ถูกซ่อนไว้) ให้ ซึ่ง serializer ที่ใช้ reflection มักจะต้องการสิ่งนี้
สุดท้ายนี้ ถ้าคุณรู้ว่าคุณจะทำงานร่วมกับ component F# อื่นๆ เท่านั้น คุณสามารถใช้ serializer เฉพาะของ F# อย่าง FsPickler [31] หรือ Chiron [32] ก็ได้ ทั้งนี้ควรสังเกตว่าการทำแบบนี้จะทำให้เกิด coupling ระหว่าง bounded contexts ขึ้นมา เพราะทุก bounded contexts จะต้องใช้ภาษาโปรแกรมมิ่งเดียวกัน
Working with Multiple Versions of a Serialized Type (การทำงานกับหลายเวอร์ชันของ Type ที่ Serialize แล้ว)
เมื่อเวลาผ่านไป เมื่อ design มีการพัฒนา domain type อาจจำเป็นต้องเปลี่ยนแปลง ไม่ว่าจะเป็นการเพิ่ม ลบ หรือเปลี่ยนชื่อ field ซึ่งก็อาจส่งผลกระทบต่อ DTO type ด้วยเช่นกัน DTO type ทำหน้าที่เป็นสัญญาระหว่าง bounded contexts และสิ่งสำคัญคือต้องไม่ทำลายสัญญานี้ นั่นหมายความว่าคุณอาจต้องรองรับ DTO type หลายเวอร์ชันไปพร้อมๆ กันตามกาลเวลา มีหลายวิธีในการทำแบบนี้ แต่เราไม่มีพื้นที่พอจะลงรายละเอียดในที่นี้ หนังสือของ Greg Young เรื่อง Versioning in an Event Sourced System, [33] มีการพูดถึงแนวทางต่างๆ ที่มีให้เลือกใช้ไว้อย่างดี
