为从其他服务返回的每一行调用服务并合并结果



我正在尝试调用一个服务,假设 Service1,它返回一个列表,然后为每行调用另一个服务 Service2 一次。然后我想合并两个结果。

因此,第一个服务返回一个数组列表,其字段在接口中定义。说:

interface Service1 {
primaryKey1 : string;
primaryKey2 : string;
value1      : string;
} 

然后,需要从第二个服务中检索具有更多值的另一个服务。

interface Service2 {
value2 : string;
value3: string;
}

此服务可以为从 Service1 返回的每一行返回几行。并且需要合并它们,以便将 Service1 中的值合并到从 Service2 返回的每一行中。

我们最终会得到一个包含以下值的列表:

interface result {
primaryKey1 : string;
primaryKey2: string;
value1 : string;
value2 : string;
value3 : string;
}

增加这种复杂性的事实是,对第二个服务的所有调用都需要按顺序调用,因为该服务一次只允许一个调用。不是您想要的并发。

所以我的问题是。我将如何在 TypeScript 中以良好的方式构建它?我真的不知道从哪里开始。我目前正在调用像this.executeRequest(request_service1).then((response) => {});这样的服务,然后我创建一个堆栈,其中包含下一个服务的输入,并执行所有这些服务。但是我在创建初始列表然后将所有结果合并到同一列表中时遇到问题。代码最终结构非常差。

编辑:根据要求,以下是可以返回的数据示例:

服务1结果:

var service1_result : Service1[] = [
{ primaryKey: "1", primaryKey2: "A", value1: "test"},
{ primaryKey: "1", primaryKey2: "B", value1: "test2"},
{ primaryKey: "2", primaryKey2: "A", value1: "test3"},
]

服务2结果:

var service2_result : Service2[] = [
{ value2: "abc", value3: "efg"},
{ value2: "abc2", value3: "efg2"},
{ value2: "abc3", value3: "efg3"},
]

请注意,Service2 将为service1_result中的每一行返回一次此类数组。他们需要链接到他们被要求的行。

编辑:所以流程看起来像这样:

  1. 呼叫服务1
  2. 对于服务 1 中的每一行,将该结果用作服务 2 的输入。
  3. 合并数据,以便从 Service2 返回的每一行都成为包含来自两个服务的所有值的行。

如果 Service1 中的前两行全部返回 Service2 中的所有行,而第三行仅返回 Service2 中的第一行,则响应如下所示:

[
{"1", "A", "Test", "abc", "efg"},
{"1", "A", "Test", "abc2", "efg2"},
{"1", "A", "Test", "abc3", "efg3"},
{"1", "B", "Test2", "abc", "efg"},
{"1", "B", "Test2", "abc2", "efg2"},
{"1", "B", "Test2", "abc3", "efg3"},
{"2", "A", "Test3", "abc", "efg"},
]

操场算法可以看起来像这样。结果是二维数组 (service1xservice2)。首先,我调用服务 1,然后将结果映射到调用服务 2 返回的结果。最后,我正在迭代所有内容并将其映射到合并的对象。您可以使其更简洁,并将映射 lambda 划分为单独的命名函数,这取决于您。让我知道这是否是您一直在寻找的,或者我应该编辑回复。

假设您只想将两个列表中的每个项目合并在一起(即zip那些数组)这样的东西应该可以解决问题

interface Service1Response {
primaryKey1: string;
primaryKey2: string;
value1: string;
}
interface Service2Response {
value2: string;
value3: string;
}
interface MergedResult extends Service1Response, Service2Response {}
async function service1Mock(): Promise<Service1Response[]> {
return [
{ primaryKey1: "1", primaryKey2: "A", value1: "test" },
{ primaryKey1: "1", primaryKey2: "B", value1: "test2" },
{ primaryKey1: "2", primaryKey2: "A", value1: "test3" }
];
}
async function service2Mock(): Promise<Service2Response[]> {
return [
{ value2: "abc", value3: "efg" },
{ value2: "abc2", value3: "efg2" },
{ value2: "abc3", value3: "efg3" }
];
}
async function callServices(): Promise<MergedResult[]> {
const response1 = await service1Mock();
const response2 = await service2Mock();
return response1.map((item1, index) => ({ ...item1, ...response2[index] }));
}
callServices()
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});

最新更新