javascript - Graph db 设计到 GraphQL 模式

标签 javascript graph graphql graphql-js

我正在尝试从我拥有的图形数据库模式创建一个 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”添加到 friend 字段中。我在文档或互联网中没有找到任何内容。

规范中是否有某些内容,或者我需要根据添加“since”等附加属性并使用它们的节点为所有边创建新类型。 或者还有其他我无法弄清楚的事情?

最佳答案

示例中继应用程序的架构 star-wars项目在这种特殊情况下非常有帮助。在您的案例中,FactionShip 分别扮演PersonFriend 的 Angular 色。

你是对的。为了包含 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-custom-datetype 。不过我还没用过。 在您已经定义的 personType 中,对于 friends 字段,列表元素类型 personType 需要替换为新的 friendType :

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

如果好友数量较多,建议使用连接或边缘,正如 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),
},

关于javascript - Graph db 设计到 GraphQL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36302536/

相关文章:

javascript - react-dom 爆出 webpack 包的大小

javascript - ES6类构建

javascript - 将子字段提升到投影的顶级,而不列出所有键

javascript - 当用户单击选择标签上的“提交”时,如何使 "select one"选项不通过?

graph - 绘制非常大的图形

python - 查找具有 n 个节点的所有不同图(networkx)

python - 在TensorFlow中显示图形图像?

express - 突变上的未定义参数,使用 apollo-server

node.js - 从解析器内部获取完整的查询字符串

GraphQL - 在联合中使用不同类型的相同字段名称