2017-05-08 49 views
1

我在探索graphql,而困扰着我的问题是如果我在定义我的graphql服务器时可以做某种类型的组合。GraphQL类型组合

我们假设我的收藏中有Person和Company。我有这样的事情:

const Person = new GraphQLObjectType({ 
    name: 'Person', 
    fields: { 
    firstName: {type: GraphQLString}, 
    lastName: {type: GraphQLString} 
    } 
}); 

const Company = new GraphQLObjectType({ 
    name: 'Company', 
    fields: { 
    name: {type: GraphQLString}, 
    website: {type: GraphQLString} 
    } 
}); 

但无论单位和个人应该有这样的字段:createdAtid。因此,假设我有:

const Entity = new GraphQLObjectType({ 
    name: 'Entity', 
    fields: { 
    id: {type: GraphQLString}, 
    createdAt: {type: GraphQLString} 
    } 
}); 

,所以我想是这样的:

new GraphQLObjectType({ 
    ... 
    extends: [Entity] 
}); 

我知道有interfaces,但我认为这不是我所期待的,因为那时我需要实现接口无论如何,我想达到的目的是保留一些字段定义sepratly并重用其他类型。

任何想法?我在做什么完全没有意义的事情?

+0

看不到downvoting的原因。也许这样做的人可以写出什么不清楚或为什么你认为它没有用?或者你声称我没有做出研究工作?任何解释? – jano

回答

0

如果我们看看GraphQL语言规范,有接口。接口用于描述两种类型的常见行为。如果您在同一个字段中返回两个子类型,接口通常才有意义。 GraphQL documentation就是一个很好的例子。我建议不要在你的情况下使用接口,除非你想在同一个字段中返回所有实体类型(例如在搜索中)。

您正在谈论服务器实施级别。我不知道在GraphQL.js中扩展类似这样的类型。你可以做的是创建一个包含两个字段的JavaScript对象。然后,您可以重复使用此代码,并将其插入到所有类型的,例如使用Object.assign

const standardFields = { 
    id: { 
     type: new GraphQLNonNull(GraphQLID), 
     description: 'Unique id for this entity' 
    }, 
    createdAt: { 
     type: new GraphQLNonNull(GraphQLString), 
     description: 'Datetime of this entity\'s creation' 
    } 
    } 

    const Company = new GraphQLObjectType({ 
    name: 'Company', 
    fields: Object.assign({}, standardFields, { 
     name: {type: GraphQLString}, 
     website: {type: GraphQLString} 
    } 
    }); 

也许导入从一个文件中的字段,并明确将其插入:

const { id, createdAt } = require('./standardFields'); 

    const Company = new GraphQLObjectType({ 
    name: 'Company', 
    fields: { 
     id, 
     createdAt, 
     name: {type: GraphQLString}, 
     website: {type: GraphQLString} 
    } 
    }); 

在这两种情况下,我不从中看到很多收益。建立一个确保所有类型包含字段的测试可能会更有用。

+0

这正是我目前正在做的,但我不太喜欢这个解决方案,因为在这种情况下'id'和'createdAt'不是自包含的。 – jano

+0

这可能是一个典型的“继承或组合”问题。你在寻找什么样的模式,它在实际的API中没有表现出来。所以我们不得不去问两个问题。避免代码重复?可测试性?为什么你在这里寻找继承,如果不仅仅是为了它的缘故?我不会担心它太多,在我们的应用程序中,我们实际上明确地重复了这些字段。这为我们提供了一个易于理解的具有显式依赖性的代码。 – Herku

0

您可以从interface类型得到的字段是这样的:

const carInterface = new GraphQLInterfaceType({ 
    name: 'car', 
    fields: { 
    _id: { type: GraphQLID }, 
    userId: { type: GraphQLID }, 
    carType: { type: new GraphQLNonNull(GraphQLString), description: 'نوع اعلان السيارة' }, 
    title: { type: new GraphQLNonNull(GraphQLString), description: 'عنوان الاعلان' }, 
    brand: { type: GraphQLString, description: 'الماركة-النوع' }, 
    model: { type: GraphQLString, description: 'الموديل' } 
    } 
}); 
console.log(carInterface._typeConfig.fields); 

您可以轻松地添加carInterface._typeConfig.fields任何GraphQLObject字段定义;