首页 文章

graphql 's ID type necessary if I' ve是否在Apollo Client中使用dataIdFromObject设置了唯一标识符

提问于
浏览
12

我'm using graphql + mysql + react-apollo and here'是 User 表的graphql类型之一:

type User {
  id: ID!
  name: String!
}

我在 graphqlID scalar type 的问题是,当mysql中的主键是 int 时,它会以字符串形式返回,并且它在前端创建了一些类型冲突 .

我可以根本不使用ID标量类型,因为我已经为Apollo Client中的每个对象设置了 dataIdFromObject 的唯一标识符:

import {InMemoryCache} from 'apollo-cache-inmemory';

const apolloMemoryCache = new InMemoryCache(
    {
        dataIdFromObject: ({id,__typename}) => {

          return __typename+id

        }
    }
);

const client = new ApolloClient({
   link: ApolloLink.from([authLink, httpLink]),
   cache: apolloMemoryCache,
 });

你会保留ID类型还是只丢弃它?

3 回答

  • 3

    您询问

    你会保留ID类型还是只丢弃它

    我通常建议保留ID类型,而不是向客户端公开您正在使用的整数 . 如果这是一个新的数据集,你甚至可能会更好地使用uuids作为偏移量的PK . 它会变得“更安全”,“更安全”,因为你不太可能不小心让某人访问别人的东西 .

    无论哪种方式,我建议根据中继规范使ID“不透明”,这样您就可以在以后更改它们,如果您更改数据存储区,而不会影响您的客户端 . 应用程序通常会进行自己的类型检查,因此您希望尽可能确保您的内容在这方面不会发生变化 .

  • 4

    您应该为解析器定义自定义标量 .

    在你的解析器中你应该为 ID 添加一个你期望int的地方,或者你可以在解析器中的int和string之间进行转换 .

    import { GraphQLScalarType } from 'graphql';
    
    const resolverMap = {
      ID: new GraphQLScalarType({
        name: 'ID',
        description: 'Numeric custom scalar type',
        parseValue(value) {
          let result;
          // Implement your own behavior here by setting the 'result' variable
          return result;
        },
        serialize(value) {
          let result;
          // Implement your own behavior here by setting the 'result' variable
          return result;
        },
        parseLiteral(ast) {
          switch (ast.kind) {
          // Implement your own behavior here by returning what suits your needs
          // depending on ast.kind
          }
        }
      }),
    };
    

    https://github.com/apollographql/graphql-tools/blob/master/docs/source/scalars.md#custom-graphqlscalartype-instance

  • 0

    试试这个而不是 type User { id: Int! name: String! }

相关问题