代码之家  ›  专栏  ›  技术社区  ›  VikR

Apollo GraphQL:查询返回不同类型对象的模式?

  •  1
  • VikR  · 技术社区  · 8 年前

    我有三个不同的PostGres表,每个表包含不同类型的同事。数据库字段对于每种类型都是不同的——这就是为什么它们位于三个单独的表中。

    我有一个组件可以访问任何类型的关联。现在,从我迄今为止遇到的示例来看,组件通常与一个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查询只能返回一个 类型

    getOneAssociate(associateType: String): [associateAccountingType]
    

    有没有可能设计一个GraphQL模式,使得单个查询可以返回不同类型的对象?解析器可以接收associateType参数,该参数将告诉它要引用哪个postGres表。但是,模式应该是什么样子的,这样它就可以根据需要返回类型为associateAccountingType、associateArtDirectorType、AsssociateAccountExecType等的对象?

    提前感谢所有人提供任何信息。

    1 回复  |  直到 8 年前
        1
  •  5
  •   davidyaha    8 年前

    这里有两种选择。 声明一个接口作为返回的类型,并确保每个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服务器和客户机实际的具体类型是什么。对于apollo,您需要在联合/交互类型上提供__resolveType函数:

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

    associate 参数将是从父解析程序返回的实际对象。 context 是您的常用上下文对象,并且 info 保存查询和模式信息。