const isoDateRE = /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/ ; function isDate ( value ) { return value && isoDateRE . test ( value ) && ! isNaN ( Date . parse ( value ) ) ; } export const format = { /** Takes a plain old JavaScript object and turns it into a Dynamodb object */ to ( object ) { const newObject = { } ; for ( const key in object ) { const value = object [ key ] ; if ( value instanceof Date ) { if ( key === "expires" ) newObject [ key ] = value . getTime ( ) / 1000 ; else newObject [ key ] = value . toISOString ( ) ; } else newObject [ key ] = value ; } return newObject ; } , /** Takes a Dynamo object and returns a plain old JavaScript object */ from < T = Record < string , unknown > > ( object ? ) { if ( ! object ) return null ; const newObject = { } ; for ( const key in object ) { if ( [ "pk" , "sk" , "GSI1PK" , "GSI1SK" ] . includes ( key ) ) continue ; const value = object [ key ] ; if ( isDate ( value ) ) newObject [ key ] = new Date ( value ) ; else if ( key === "type" && [ "SESSION" , "VT" , "USER" ] . includes ( value ) ) continue ; else if ( key === "expires" && typeof value === "number" ) newObject [ key ] = new Date ( value * 1000 ) ; else newObject [ key ] = value ; } return newObject as T ; } , } ; export function generateUpdateExpression ( object ) { const formatedSession = format . to ( object ) ; let UpdateExpression = "set" ; const ExpressionAttributeNames = { } ; const ExpressionAttributeValues = { } ; for ( const property in formatedSession ) { UpdateExpression += ` #${ property } = :${ property },` ; ExpressionAttributeNames [ "#" + property ] = property ; ExpressionAttributeValues [ ":" + property ] = formatedSession [ property ] ; } UpdateExpression = UpdateExpression . slice ( 0 , - 1 ) ; return { UpdateExpression , ExpressionAttributeNames , ExpressionAttributeValues , } ; }