我'm using graphql + mysql + react-apollo and here'是 User
表的graphql类型之一:
type User {
id: ID!
name: String!
}
我在 graphql
中 ID 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 回答
您询问
我通常建议保留ID类型,而不是向客户端公开您正在使用的整数 . 如果这是一个新的数据集,你甚至可能会更好地使用uuids作为偏移量的PK . 它会变得“更安全”,“更安全”,因为你不太可能不小心让某人访问别人的东西 .
无论哪种方式,我建议根据中继规范使ID“不透明”,这样您就可以在以后更改它们,如果您更改数据存储区,而不会影响您的客户端 . 应用程序通常会进行自己的类型检查,因此您希望尽可能确保您的内容在这方面不会发生变化 .
您应该为解析器定义自定义标量 .
在你的解析器中你应该为
ID
添加一个你期望int的地方,或者你可以在解析器中的int和string之间进行转换 .https://github.com/apollographql/graphql-tools/blob/master/docs/source/scalars.md#custom-graphqlscalartype-instance
试试这个而不是
type User { id: Int! name: String! }