dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
45 lines (44 loc) • 2.1 kB
JavaScript
import { DynamoDBToolboxError } from '../../../errors/index.js';
import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js';
import { isArray } from '../../../utils/validation/isArray.js';
import { schemaFormatter } from './schema.js';
import { matchTupleProjection } from './utils.js';
export function* tupleSchemaFormatter(schema, rawValue, { attributes, valuePath, ...restOptions } = {}) {
const { format = true, transform = true } = restOptions;
if (!isArray(rawValue)) {
const { type } = schema;
const path = valuePath !== undefined ? formatArrayPath(valuePath) : undefined;
throw new DynamoDBToolboxError('formatter.invalidAttribute', {
message: `Invalid attribute detected while formatting${path !== undefined ? `: '${path}'` : ''}. Should be a ${type}.`,
path,
payload: { received: rawValue, expected: type }
});
}
const formatters = [];
let projectedIndex = 0;
schema.elements.forEach((element, elementIndex) => {
const { isProjected, childrenAttributes } = matchTupleProjection(elementIndex, attributes);
if (isProjected) {
formatters.push(isProjected
? schemaFormatter(element, rawValue[projectedIndex], {
attributes: childrenAttributes,
valuePath: [...(valuePath !== null && valuePath !== void 0 ? valuePath : []), elementIndex],
...restOptions,
...(!isProjected ? { defined: false } : {})
})
: undefined);
projectedIndex++;
}
});
if (transform) {
const transformedValue = formatters.map(formatter => formatter === null || formatter === void 0 ? void 0 : formatter.next().value);
if (format) {
yield transformedValue;
}
else {
return transformedValue;
}
}
const formattedValue = formatters.map(formatter => formatter === null || formatter === void 0 ? void 0 : formatter.next().value);
return formattedValue;
}