reactjs - 如何使用全局ID?

标签 reactjs relayjs graphql-js

当每次加载时 id 都不同时,我该如何(重新)查询对象? 我错过了什么?

const {nodeInterface, nodeField} = nodeDefinitions(
  (globalId) => {
    const {type, id} = fromGlobalId(globalId);

    // This id is different every time (if page is reloaded/refreshed)
    // How am I suppose to use this id for database query (e.g by id)?
    // How do I get "the right ID"? (ID actually used in database)
    console.log('id:', id);

    // This is correct: "User"
    console.log('type:', type);

    if (type === 'User') {
        // Function that is suppose to get the user but id is useless ..
        return getUserById(id);
    } 
    return null;
  },

  (obj) => {
    if (obj instanceof User) {
        return userType;
    } 
    return null;
  }
);

const userType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
      id: globalIdField('User'),      // Relay ID
      _id:   { type: GraphQLString }, // MongoDB ID
      email: { type: GraphQLString },
      name:  { type: GraphQLString }    
  }),
  interfaces: [nodeInterface]
});

最佳答案

全局 ID 主要用于重新获取 Relay 客户端存储中已有的对象。我将干燥并指向 an excellent related SO post ,这很好地解释了 Relay 中如何使用全局 ID。

如果您使用库中的辅助函数,例如 graphql-relay-js在 JavaScript 中,处理全局 ID 变得非常简单:

  1. 您确定服务器端对象类型 X 对应于 GraphQL 对象类型 Y。
  2. 向 X 添加一个字段 id。此 id 是本地 ID,对于 X 类型的任何对象都必须是唯一的。如果 X 对应于 MongoDB 文档类型,那么一个简单的方法是将 _id 的字符串表示形式分配给此 id 字段:instanceOfX.id = dbObject._id.toHexString() .
  3. 使用 globalIdField 辅助函数向 Y 添加字段 id。这个id是全局ID,它在所有类型和对象中都是唯一的。如何生成这个全局唯一 ID 字段取决于实现。 globalIdField 辅助函数根据对象 X 中的 id 字段和类型名称 X 生成此值。
  4. nodeDefinitions 中,使用 fromGlobalId 辅助函数从全局 ID 检索本地 ID 和类型。由于X中的id字段是MongoDB中的_id字段,因此您可以使用此本地ID来执行DB操作。首先从十六进制字符串转换为 MongoDB ID 类型。

您的实现中必须破坏本地 ID 分配(步骤 2)。否则,同一对象的 ID 在每次重新加载时都不会不同。

关于reactjs - 如何使用全局ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834567/

相关文章:

graphql - Apollo:从远程模式扩展类型

javascript - 具有自定义标量类型的 GraphQL.js 突变

javascript - 在 react 中添加变量以要求

javascript - styled-components:扩展样式和改变元素类型

reactjs - React Native 复用设置状态的函数

javascript - 由于 ES2015 模板文字导致的 Webpack 错误 - "Unterminated string constant"

javascript - 将额外的页面推送到历史记录

javascript - 使用 babel-relay-plugin 时出错

graphql - 如何在 GraphQL 解析器中获取请求的字段?