GraphQL模式的图形数据库设计

Graph db design to GraphQL schema

本文关键字:图形数据库 模式 GraphQL      更新时间:2023-09-26

我正试图从我拥有的图形数据库模式创建一个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"添加到friends字段中。我在文件或互联网上找不到任何东西。

规范中有什么东西吗?或者我需要根据节点为所有边创建新的类型,添加诸如"since"之类的附加属性并使用它们。还是其他我想不通的事情?

示例中继应用程序的模式,在这种特殊情况下的星球大战项目,非常有用。FactionShip在您的案例中扮演PersonFriend的角色。

你是对的。为了包含since属性,可以为friend引入一种新的类型,如下所示(使用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自定义日期类型。不过我没有用过。在您已经定义的personType中,对于friends字段,列表元素类型personType需要替换为新的friendType:

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

如果朋友数量很大,建议连接或边缘,正如ykad4已经建议的那样。一旦我们有了Friend的定义,我们就可以如下定义它的连接:

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

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

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