func AddItemIntoDatabaseIfNotExist()

in util/awsservice/dynamodb.go [30:54]


func AddItemIntoDatabaseIfNotExist(databaseName string, checkingAttribute, checkingAttributeValue []string, packet map[string]interface{}) error {
	item, err := attributevalue.MarshalMap(packet)
	if err != nil {
		return err
	}

	// DynamoDb only allows query two conditions key. Therefore, only needs an array with length 2
	// https://stackoverflow.com/questions/65390063/dynamodbexception-conditions-can-be-of-length-1-or-2-only
	_, err = DynamodbClient.PutItem(ctx,
		&dynamodb.PutItemInput{
			Item:                item,
			TableName:           aws.String(databaseName),
			ConditionExpression: aws.String("#first_attribute <> :first_attribute and #second_attribute <> :second_attribute"),
			ExpressionAttributeNames: map[string]string{
				"#first_attribute":  checkingAttribute[0],
				"#second_attribute": checkingAttribute[1],
			},
			ExpressionAttributeValues: map[string]types.AttributeValue{
				":first_attribute":  &types.AttributeValueMemberS{Value: checkingAttributeValue[0]},
				":second_attribute": &types.AttributeValueMemberS{Value: checkingAttributeValue[1]},
			},
		})

	return err
}