@onereach/orest-input-cli
Version:
The tool for creating, serving, and publishing OREST Inputs
118 lines (103 loc) • 2.38 kB
JavaScript
import {
hasNotVariable,
isSpreadContainer,
} from '@onereach/orest-inputs-utils';
export const getFnByUrn = async ({ children, resolvers, resolverName }) => {
const uniqInputUrns = Array.from(new Set(children.map(({ urn }) => urn)));
const fnAndUrns = await Promise.all(
uniqInputUrns.map(inputUrn =>
resolvers[resolverName](inputUrn).then(fn => ({
inputUrn,
fn,
}))
)
);
return fnAndUrns.reduce(
(acc, { inputUrn, fn }) => ({
...acc,
[inputUrn]: fn,
}),
{}
);
};
export const getResolvedChildren = async ({
children,
resolvers,
resolverName,
restArgs,
runtimeArgs,
}) => {
const fnByUrn = await getFnByUrn({
children,
resolvers,
resolverName,
});
const resolvedChildrenFlat = await Promise.all(
children.map(child => {
const fn = fnByUrn[child.urn];
return fn(child.value, ...restArgs)
.then(fn => fn(...runtimeArgs))
.then(result => ({
result,
child,
}));
})
);
return resolvedChildrenFlat
.map(({ result, child }) => {
if (isSpreadContainer(child.value) || hasNotVariable(child.value)) {
return result;
}
if (child.value.variable) {
return { [child.value.variable]: result };
}
})
.filter(item => item !== undefined);
};
export const getNormalizedResolvedChildren = async ({
children,
resolvers,
resolverName,
restArgs,
runtimeArgs,
value,
}) => {
const fnByUrn = await getFnByUrn({
children,
resolvers,
resolverName,
});
const resolvedChildrenFlat = await Promise.all(
children.map((child, index) => {
const fn = fnByUrn[child.urn];
return fn(child.value, ...restArgs)
.then(fn => fn(...runtimeArgs))
.then(fn =>
fn(
child.value.variable
? value?.[index]?.[child.value.variable]
: value?.[index]
)
)
.then(result => ({
result,
child,
}));
})
);
return resolvedChildrenFlat.reduce((acc, { result, child }) => {
if (isSpreadContainer(child.value)) {
return {
...acc,
...result,
};
}
if (child.value.variable) {
return {
...acc,
[child.value.variable]: result,
};
}
return acc;
}, {});
};