Resolved with answers, thanks everyone
EDIT :
I want my updateInventory function to return an object that have a property for each promise.
I can not know neither which ones will be used nor the order
The problem is that t.batch and Promise.all return an index array so I can not associate a promise to its component to output an object like I want.
Inspired by this post I did this:
The then in getStatement is executed first to format the resulting data of each promise : an object with name and data properties.
Then t.batch is resolved with all of these objects. The result is still an index array but each object contains the name and the data.
So I can create my final object.
Maybe there is a better way to do it ?
An example below : My input :
{
device: {
deviceId: 1,
name: "myName",
istate: "updated"
},
system: {
systemId: 50,
domain: 'foo.fr',
istate: "updated"
},
ifaces: [
{
interfaceId: 75,
name: "Iface Update 1",
istate: "updated"
},
{
name: "New Interface 1",
istate: "added"
}
]
}
"standard" Output with only t.batch() or `Promise.all() : an index array
[
0: { deviceId: 1 },
1: { systemId: 50 },
2: [
{ interfaceId: 75 },
{ interfaceId: 76 }
]
]
My custom t.batch output :
[
0: { name: "device", data: { deviceId: 1 }}
1: { name: "system", data: { systemId: 50 }}
2: { name: "ifaces", data: [{ interfaceId: 75 },{ interfaceId: 76 }] }
]
And then I can build my final object (values.forEach below) :
{
"device": { deviceId: 1 },
"system": { systemId: 50 },
ifaces: [
{ interfaceId: 75 },
{ interfaceId: 76 }
]
}
The code (simplified):
function updateInventory(params) {
const { /* hidden */, ...components } = params.data; // simplified
return Database.tx('Inventory-Update', t => { // postgres transaction with pg-promise library
const statements = []; // promise array
for(let [prop, component] of Object.entries(components)) {
statements.push(getStatement(t, prop, component));
}
return t.batch(statements);
}).then(results => {
let result = {};
results.forEach(res => {
result[res.name] = res.data;
});
return result;
});
}
function getStatement(t, prop, component) {
const repo = getReposName(prop);
const state = component.istate;
let statement;
switch(state) {
case "updated":
statement = t[repo].update(component);
break;
case "removed":
statement = t[repo].delete(component);
break;
default:
statement = t[repo].insert(component);
break;
}
return statement.then(res => {
return {name: prop, data: res };
});
}