在创建帖子时,我将此响应发送到API
"postSummary":"Immediate",
"locations":[
{
"spSubLocationCode":"CH1",
"spSubLocationName":"IGT"
}
],Location是一个下拉列表,是检索到的location,其中名称定义为spSubLocationCode。但在向API发布响应时,他们需要以下格式的响应。
但是api期望:
"announcementSummary":"Immediate",
"locations" : [{
"locationCode":"terminalCode-9",
"locationName":"terminalName-9"
}],ts代码
const publishReq = {
locations: postSummary.locations.filter(
(val: string) => val != 'selectAlllocations'
),
postType: postSummary.postType
};
createpost(publishReq)发布于 2020-09-10 15:33:57
快速而简单的解决方案是只编写一个函数,该函数接受您的格式并输出所需的格式:
function toApiLocationCode(value) {
// Here you will have to implement mapping from stuff like 'CH1' to 'terminalCode-9'
switch (value) {
case 'CH1':
return 'terminalCode-9';
calse 'IGT':
return 'terminalName-9';
default:
throw Error(`Unknown location code: ${value}`);
}
}
function toApiLocation(locationObject) {
return {
locationCode: toApiLocationCode(locationObject.spSubLocationCode),
locationName: toApiLocationCode(locationObject.spSubLocationName)
};
}
function toApiPayload(yourFormat) {
return {
"announcementSummary": yourFormat.postSummary,
"locations": yourFormat.locations.map(toApiLocation)
};
}然而,这是相当脏的。既然你正在使用Typescript,那么最好为这个用例编写类和枚举:
class DomainObject {
constructor(
public readonly postSummary: PostSummary,
public readonly locations: Array<DomainLocation>
) {}
public toApiObject() {
return new ApiObject(
this.postSummary,
this.locations.map(location => location.toApiLocation())
);
}
}
class DomainLocation {
constructor(
public readonly spSubLocationCode: string,
public readonly spSubLocationName: string
) {}
public toApiLocation() : ApiLocation {
return new ApiLocation(
mapDomainLocationCodeToApiLocationCode(this.spSubLocationCode),
mapDomainLocationNameToApiLocationName(this.spSubLocationName)
);
}
}
enum PostSummary {
IMMEDIATE = 'Immediate'
}
class ApiObject {
constructor(
public readonly announcementSummary: PostSummary,
public readonly locations: Array<ApiLocation>
) {}
}
class ApiLocation {
constructor(
public readonly locationCode: string,
public readonly locationName: string
) { }
}
function mapDomainLocationCodeToApiLocationCode(value: string) {
switch (value) {
case 'CH1':
return 'terminalCode-9';
default:
throw new Error(`Location code '${value}' does not have an API code mapping.`);
}
}
function mapDomainLocationNameToApiLocationName(value: string) {
switch (value) {
case 'IGT':
return 'terminalName-9'
default:
throw new Error(`Location name '${value}' does not have an API name mapping`);
}
}https://stackoverflow.com/questions/63824180
复制相似问题