2016-11-12 7 views
1

나는 서로 다른 PostGres 테이블을 가지고있다. 데이터베이스 필드는 각 유형별로 다르기 때문에 세 개의 개별 테이블에 있습니다.Apollo GraphQL : 다른 유형의 객체를 반환하는 쿼리의 스키마?

잠재적으로 모든 유형의 연관에 액세스 할 수있는 하나의 구성 요소가 있습니다.

const withData = graphql(GETONEASSOCIATE_QUERY, { 
    options({ navID }) { 
     return { 
      variables: { _id: navID} 
     }; 
    } 
    , 
    props({ data: { loading, getOneAssociate } }) { 
     return { loading, getOneAssociate }; 
    }, 


}); 

export default compose(
    withData, 
    withApollo 
)(AssociatesList); 

그리고가 주어진 GraphQL 쿼리 것을, 단 하나의 을 반환 할 수 있습니다 나타납니다 : 이제 구성 요소는 일반적으로 하나 개 GraphQL 쿼리, 예를 들어 연결되어 있는지, 내가 지금까지 만난 예에서 보인다 레코드의을 입력하십시오. 스키마 :

getOneAssociate(associateType: String): [associateAccountingType] 

질문 :는 단일 쿼리가, 다른 유형의 객체를 반환 할 수 이러한 GraphQL 스키마를 설계 할 수있다? 해석자는 참조 할 postGres 테이블을 알려주는 associateType 매개 변수를받을 수 있습니다. 하지만 스키마는 어떨까요? associateAccountingType, associateArtDirectorType, associateAccountExecType 등의 객체를 필요에 따라 반환 할 수 있도록하려면 어떻게해야할까요?

모든 정보에 대해 미리 감사드립니다.

답변

4

두 가지 옵션이 있습니다. 리턴 된 유형으로 Interface를 선언하고이 각각의 associateTypes가 해당 인터페이스를 확장하는지 확인하십시오. 이러한 모든 유형의 공통 필드가 함께있는 경우에 좋은 방법입니다. 너무처럼 보일 것입니다 : 당신이 어떤 공통 필드가 없거나 오히려 어떤 이유로 관련이없는 그 유형이 줄 경우 노동 조합 유형을 사용할 수 있습니다

interface associateType { 
    id: ID 
    department: Department 
    employees: [Employee] 
} 

type associateAccountingType implements associateType { 
    id: ID 
    department: Department 
    employees: [Employee] 
    accounts: [Account] 
} 

type associateArtDirectorType implements associateType { 
    id: ID 
    department: Department 
    employees: [Employee] 
    projects: [Project] 
} 

. 이 선언은 훨씬 간단하지만 엔진에서 이러한 유형에 공통 필드가 없다고 가정 할 때 쿼리하는 각 필드에 대해 조각을 사용해야합니다.

union associateType = associateAccountingType | associateArtDirectorType | associateAccountExecType 

한 가지 더 중요한 것은 실제 구체적인 유형이 무엇인지 당신 graphql 서버와 클라이언트를 알려주는 해결을 구현하는 방법이 될 것입니다. 아폴로를 들어, 노동 조합/interace 유형에 __resolveType 기능을 제공해야합니다 :

{ 
    associateType: { 
    __resolveType(associate, context, info) { 
     return associate.isAccounting ? 'associateAccountingType' : 'associateArtDirectorType'; 
    }, 
    } 
}, 

이 기능을 사용하면 원하는대로 논리를 구현할 수 있지만, 당신이 사용중인 유형의 이름을 반환해야합니다. associate 인수는 부모 확인자에서 반환 한 실제 개체가됩니다. context은 일반적인 컨텍스트 개체이고 info은 쿼리 및 스키마 정보를 보유합니다.