import { PutItemInput , Converter } from 'aws-sdk/clients/dynamodb' ; import { AWSError } from 'aws-sdk/lib/error' ; import { Context } from '../context' ; import { getCollection , toWrapped , assemblePrimaryKeyValue , } from '../base/util' ; import { ConflictException } from '../base/exceptions' ; import get from 'lodash/get' ; import { DocumentWithId } from '../base/common' ; import debugDynamo from '../debug/debugDynamo' ; param context param collectionName param value returns throws export async function insert < DocumentType extends DocumentWithId > ( context , collectionName , value ) { const collection = getCollection ( context , collectionName ) ; const wrapped = toWrapped < DocumentType > ( collection , value ) ; let request ; if ( collection . type === 'child' ) { request = { TableName : collection . layout . tableName , Item : Converter . marshall ( wrapped ) , ReturnValues : 'NONE' , ConditionExpression : 'attribute_not_exists(#parentIdAttribute) and attribute_not_exists(#childIdAttribute)' , ExpressionAttributeNames : { '#parentIdAttribute' : assemblePrimaryKeyValue ( collection . parentCollectionName , get ( value , collection . foreignKeyPath ) , collection . layout . indexKeySeparator ) , '#childIdAttribute' : assemblePrimaryKeyValue ( collection . name , wrapped . value . _id , collection . layout . indexKeySeparator ) , } , } ; } else { request = { TableName : collection . layout . tableName , Item : Converter . marshall ( wrapped ) , ReturnValues : 'NONE' , ConditionExpression : 'attribute_not_exists(#idAttribute)' , ExpressionAttributeNames : { '#idAttribute' : assemblePrimaryKeyValue ( collection . name , wrapped . value . _id , collection . layout . indexKeySeparator ) , } , } ; } try { debugDynamo ( 'PutItem' , request ) ; await context . ddb . putItem ( request ) . promise ( ) ; } catch ( error ) { if ( ( error as AWSError ) . code === 'ConditionalCheckFailedException' ) { throw new ConflictException ( 'An item with this _id already exists' , wrapped . value . _id ) ; } throw error ; } return wrapped . value ; }