图形数据库设计到 GraphQL 模式

Graph db design to GraphQL schema

我正在尝试从我拥有的图形数据库模式创建一个 graphql 模式。但是我不知道如何在 graphql 模式中为我拥有的边添加属性。

在一些代码中:

示例数据库架构:

node: {
  label: 'Person',
  properties: [
   id: { type: id }
   name: { type: string }
  ]
}

edge: {
  label: 'friends'
  startNode: 'Person',
  endNode: 'Person'
  properties: {
    since: { type: date }
  }
}

在 graphql 模式中应该看起来很简单:

var personType = new graphql.GraphQLObjectType({
  name: 'personType',
  fields: function() { return {
    id: { type: graphql.GraphQLString },
    name: { type: graphql.GraphQLString },
    friends: { type: graphql.GraphQLList(personType) }
  }})
});

但我看不出有什么办法可以将 属性 'since' 添加到好友字段中。而且我没有在文档或互联网上找到任何东西。

规范中有什么内容吗?或者我需要根据添加附加属性(如 'since' 并使用它们的节点)为所有边创建新类型。 或者其他我想不通的东西?

示例中继应用程序的模式,star-wars 在这个特殊情况下的项目,非常有帮助。 FactionShip 在您的案例中扮演 PersonFriend 的角色。

你是对的。为了包含 since 属性,可以为朋友引入一个新类型,如下所示(使用 graphql npm 包):

var friendType = new GraphQLObjectType({
  name: 'Friend',
  fields: {
    id: globalIdField('Friend'),
    name: {
      type: GraphQLString,
      resolve: (friend) => friend.name,
    },
    since: {
      type: GraphQLString,
      resolve: (friend) => friend.since.toString(),
    },
  },
  interfaces: [nodeInterface],
});

friendType中,since是实际日期的字符串表示。如果你想要自定义 GraphQL 类型的日期,你可以看看 graphql-custom-datetype。我没有用过它。 在您已经定义的 personType 中,对于 friends 字段,列表元素类型 personType 需要替换为新的 friendType:

friends: { type: graphql.GraphQLList(friendType) }

如果好友数量多,推荐connection或者edge,ykad4已经推荐了。一旦我们有了 Friend 的定义,我们就可以为它定义连接,如下所示:

const {
  connectionType: friendConnection,
  edgeType: friendEdge,
} = connectionDefinitions({
  name: 'Friend',
  nodeType: friendType,
});

personType 中的字段 friends 将更新如下(使用 graphql-relay npm 包中的辅助函数):

friends: {
  type: friendConnection,
  args: connectionArgs,
  resolve: (person) => connectionFromArray(person.friends, args),
},