UNPKG

dynamodb-toolbox

Version:

Lightweight and type-safe query builder for DynamoDB and TypeScript.

33 lines (32 loc) 1.68 kB
export const sanitize = (str) => str.replace(/\\/g, '\\\\').replace(/[-[\]/{}()*+?.^$|]/g, '\\$&'); export const matchItemProjection = (attributeName, projectedAttributes) => { const sanitizedAttributeName = sanitize(attributeName); return matchProjection(new RegExp(`^(${sanitizedAttributeName}|\\['${sanitizedAttributeName}'\\])(?=\\.|\\[|$)`), projectedAttributes); }; export const matchMapProjection = (attributeName, projectedAttributes) => { const sanitizedAttributeName = sanitize(attributeName); return matchProjection(new RegExp(`^(\\.${sanitizedAttributeName}|\\['${sanitizedAttributeName}'])(?=\\.|\\[|$)`), projectedAttributes); }; export const matchListProjection = (projectedAttributes) => matchProjection(/\[\d+\]/, projectedAttributes); const matchProjection = (attributeNameRegex, projectedAttributes) => { if (projectedAttributes === undefined) { return { isProjected: true }; } const childrenAttributes = []; for (const attributePath of projectedAttributes) { const attributeMatch = attributePath.match(attributeNameRegex); if (attributeMatch !== null) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const firstMatch = attributeMatch[0]; childrenAttributes.push(attributePath.slice(firstMatch.length)); } } if (childrenAttributes.length === 0) { return { isProjected: false }; } if (childrenAttributes.some(attribute => attribute === '')) { // We do not add childrenAttributes as we want all of them return { isProjected: true }; } return { isProjected: true, childrenAttributes }; };