import { CodeGenDirective , CodeGenField , CodeGenModel , CodeGenModelMap } from '../visitors/appsync-visitor' ; import { CodeGenConnectionType , CodeGenFieldConnection , makeConnectionAttributeName , } from './process-connections' ; import { getConnectedFieldV2 } from './process-connections-v2' ; export function processHasManyConnection ( field , model , modelMap , connectionDirective , shouldUseModelNameFieldInHasManyAndBelongsTo ) { const otherSide = modelMap [ field . type ] ; const connectionFields = connectionDirective . arguments . fields || [ ] ; const otherSideField = getConnectedFieldV2 ( field , model , otherSide , connectionDirective . name , shouldUseModelNameFieldInHasManyAndBelongsTo ) ; const isNewField = ! otherSide . fields . includes ( otherSideField ) ; const isConnectingFieldAutoCreated = connectionFields . length === 0 ; if ( ! isNewField ) { if ( field . isList && ! otherSideField . isList ) { return { kind : CodeGenConnectionType . HAS_MANY , associatedWith : otherSideField , isConnectingFieldAutoCreated , connectedModel : otherSide , } ; } } else { if ( field . isList ) { const connectionFieldName = makeConnectionAttributeName ( model . name , field . name ) ; const existingConnectionField = shouldUseModelNameFieldInHasManyAndBelongsTo ? otherSide . fields . find ( f => f . name === connectionFieldName ) || otherSideField : otherSide . fields . find ( f => f . name === connectionFieldName ) ; return { kind : CodeGenConnectionType . HAS_MANY , connectedModel : otherSide , isConnectingFieldAutoCreated , associatedWith : existingConnectionField || { name : connectionFieldName , type : 'ID' , isList : false , isNullable : true , directives : [ ] , } , } ; } else { throw new Error ( "A field with hasMany must be a list type" ) ; } } }