对于 GraphQL,声明一个与 GraphQL "Type" 没有任何明显差异的支持模型 "class" 有什么好处或必要性?

With GraphQL, what is the benefit or necessity of declaring a backing model "class" that does not vary from the GraphQL "Type" in any obvious way?

我喜欢 Universal Relay Boilerplate - 总的来说,我可以看出他们对如何将整个东西组合在一起非常周到,这与文件夹组织等似乎是事后考虑的大多数样板不同(我猜是因为你一开始不会做任何重要的事情,或者什么)......但不是 URB。或者至少我们对同样的事情挑剔。

为什么 same annoying thing...

...除了一件事:我不明白他们为什么这样做。

// Class used by GraphQL Server
export default class User
{
  constructor( fields )
  {
    this.id = fields.id
    this.User_AccountName = fields.User_AccountName
    this.User_AccountPassword = fields.User_AccountPassword
    this.User_DisplayName = fields.User_DisplayName
    this.User_ProfilePhoto = fields.User_ProfilePhoto
    this.User_Email = fields.User_Email
    this.User_PhoneNumberMobile = fields.User_PhoneNumberMobile
    this.User_Locale = fields.User_Locale
    this.UserToken2 = fields.UserToken2
  }
}

...two times in close proximity with no explanation?

这里是“类型”,实际上由于别名而与原来的有点不同。

export default new GraphQLObjectType( {
  name: 'Viewer',
  interfaces: [NodeInterface],
  isTypeOf: object => object instanceof User,
  fields: {
    id: globalIdField('Viewer'),

    User_IsAnonymous:        { type: GraphQLBoolean, resolve: (obj) => obj.id.equals( Uuid_0 ) },
    User_AccountName:        { type: GraphQLString,  resolve: (obj) => obj.User_AccountName },
    User_DisplayName:        { type: GraphQLString,  resolve: (obj) => obj.User_DisplayName },
    User_ProfilePhoto:       { type: GraphQLString,  resolve: (obj) => obj.User_ProfilePhoto },
    User_Email:              { type: GraphQLString,  resolve: (obj) => obj.User_Email },
    User_PhoneNumberMobile:  { type: GraphQLString,  resolve: (obj) => obj.User_PhoneNumberMobile },
    User_Locale:             { type: GraphQLString,  resolve: (obj) => obj.User_Locale },
    UserToken2:             { type: GraphQLString,  resolve: (obj) => obj.UserToken2 },

    ..._ViewerFields,

  },
} );

他们显然是有意的

这是我能在样板文件中找到的 modeltype 之间差异最显着的例子;其他的是相同的。发现没有其他指南推荐甚至提到做 model.js 而是从 type.js.

开始,我实际上有点恼火

如果

我能理解

但他们到处都这样做,这让我觉得我在这里遗漏了一些重要的东西。

它们不是一回事。只是同名:

  • 一个是对象实例
  • 另一个是对象的结构(类型用来记录API)

可能只是样板文件没有展示这种方法的好处。我认为您已经有了一些可能有益的想法,例如,当您的后端数据模型未完全映射到您的 GraphQL 时 API.

如今许多采用 GraphQL 的组织都有一些他们习惯使用的现有后端和数据模型。在这种情况下,您可以将 GraphQL 视为另一个 API 层,位于您的 REST API 或其他任何东西旁边。 GraphQL 不是 你的实际后端 - 你不应该直接在解析器中处理你的业务逻辑,因为那样你的整个应用程序将耦合到 GraphQL。当您使用 GraphQL 从头开始​​构建新应用程序时,这一点并不清楚,但这是一个值得遵循的好模式,因为您将来可能希望灵活地使用 API。

在上图中,GraphQL 将是 "external interface." 请注意,它位于业务 logic/model 层之上,但不会取代它。

GraphQL API 中的类型是您要在 UI 中显示的数据。这可能包含不在数据库中的计算字段,某些字段可能来自多个后端等。

阅读 Dan Schafer 在我对他的 React Europe 演讲的总结中提出的这些概念:https://medium.com/apollo-stack/graphql-at-facebook-by-dan-schafer-38d65ef075af#.awusd3ibv