module import * as DynamoDB from 'aws-sdk/clients/dynamodb' ; import { isEmpty } from '../../helper/is-empty.function' ; import { isString } from '../../helper/is-string.function' ; import { ConditionalParams } from '../operation-params.type' ; import { resolveAttributeValueNameConflicts } from './functions/resolve-attribute-value-name-conflicts.function' ; import { Expression } from './type/expression.type' ; import { UpdateActionKeyword } from './type/update-action-keyword.type' ; hidden export function addUpdateExpression ( updateExpression , params ) { addExpression ( 'UpdateExpression' , updateExpression , params ) ; } hidden export function addExpression ( expressionType , condition , params ) { const nameSafeCondition = resolveAttributeValueNameConflicts ( condition , params ) ; const expressionAttributeNames = < DynamoDB . ExpressionAttributeNameMap > { ... params . ExpressionAttributeNames , ... nameSafeCondition . attributeNames , } ; const expressionAttributeValues = < DynamoDB . ExpressionAttributeValueMap > { ... params . ExpressionAttributeValues , ... nameSafeCondition . attributeValues , } ; if ( ! isEmpty ( expressionAttributeNames ) ) { params . ExpressionAttributeNames = expressionAttributeNames ; } if ( ! isEmpty ( expressionAttributeValues ) ) { params . ExpressionAttributeValues = expressionAttributeValues ; } const statement = params [ expressionType ] ; if ( isString ( statement ) && statement !== '' ) { switch ( expressionType ) { case 'UpdateExpression' : ; ( < any > params ) [ expressionType ] = mergeUpdateExpressions ( statement , nameSafeCondition . statement ) ; break ; default : ; ( < any > params ) [ expressionType ] = `${ statement } AND ${ nameSafeCondition . statement }` ; } } else { ; ( < any > params ) [ expressionType ] = nameSafeCondition . statement ; } } hidden type UpdateExpressionsByKeyword = Record < UpdateActionKeyword , string > ; hidden export function mergeUpdateExpressions ( expression1 , expression2 ) { const a = splitUpdateExpressionToActionKeyword ( expression1 ) ; const b = splitUpdateExpressionToActionKeyword ( expression2 ) ; return Array . from ( new Set ( < UpdateActionKeyword [ ] > [ ... Object . keys ( a ) , ... Object . keys ( b ) ] ) ) . map ( ( clause ) => `${ clause } ` + ( ! a [ clause ] ? b [ clause ] : ! b [ clause ] ? a [ clause ] : `${ a [ clause ] }, ${ b [ clause ] }` ) ) . join ( ' ' ) ; } hidden function splitUpdateExpressionToActionKeyword ( updateExpression ) { return ( ` ${ updateExpression }` . split ( /\s(SET|REMOVE|ADD|DELETE)\s/g ) . reduce ( ( u , e , i , arr ) => { if ( isUpdateActionKeyword ( e ) ) { u [ e ] = arr [ i + 1 ] ; } return u ; } , < UpdateExpressionsByKeyword > { } ) ) ; } hidden function isUpdateActionKeyword ( val ) { return /^(SET|REMOVE|ADD|DELETE)$/ . test ( val ) ; }