我來自Java,我通常使用DTO來映射到Entity,反之亦然。但是我很難在Typescript Nodejs中做到這一點。我有兩個介面:
export 介面 IOne {
clientId: number;
clientName: string;
...
}
export 介面 ITwo {
userId: 數字。
userName: string;
...
}
在介面一的格式上收到一個GET呼叫,介面二負責抓取這個回應并在之后發出一個POST請求。
下面的實作得到undefined:
let userTwo: ITwo;
userTwo.map(data => {
return <ITwo> {
userId: data.clientId,
userName: data.clientName。
...
};
});
在Typescript/Nodejs中,用一種介面格式映射回傳的回應,然后在DTO到域物件模式中轉換為另一種介面格式,這種方法是什么?
uj5u.com熱心網友回復:
你可以這樣做:
export 介面 IOne {
clientId: number;
clientName: string;
...
}
export 介面 ITwo {
userId: 數字。
userName: string;
...
}
const toDTO = (input: IOne)。ITwo => {
return {
userId: input.clientId,
userName: input.clientName, userName: input.clientName
}
}
const handleReq = (req)=> {
//我們假設你必須告訴Typescript什么是userOne。
const userOne = req.userOne as IOne[] 。
//userTwo將被輸入為ITwo[]或陣列<ITwo>通過推理。
const userTwo = userOne.map(u => toDTO(u)
}
uj5u.com熱心網友回復:
https://khalilstemmler.com/articles/typescript-domain-driven-design/repository-dto-mapper/
它包含了更多的細節,但它也展示了實作你所要求的良好做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/309946.html
標籤:
