何时使用 GraphQLID 而不是 GraphQLInt?
When to use GraphQLID instead of GraphQLInt?
不清楚什么时候使用GraphQLID
instead of GraphQLInt
。
考虑以下架构:
type User {
id: Int!
firstName: String!
lastName: String!
}
type Query {
user (id: ID!): User
}
在Query.user
的情况下,使用GraphQLID
还是GraphQLInt
似乎没有区别。
在 User.id
的情况下,使用 GraphQLID
会将输入转换为字符串。使用 GraphQLInt
将确保输入为整数。
这使得查询和类型系统不一致。
graphql-js spec 简单地说:
A GraphQLScalarType
that represents an ID.
这是一个实现细节吗(例如,GraphQL 客户端应该尽可能将 GraphQLID
转换为整数),还是期望 ID
始终是 graphql 中的字符串?
我查看了 GraphQL 规范。
The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String
; however, it is not intended to be human‐readable. While it is often numeric, it should always serialize as a String
.
– https://spec.graphql.org/April2016/#sec-ID
这回答了它是留给实现还是由规范规定的问题,即 ID 应始终序列化为 String
。
此外,在输入类型的上下文中,需要将输入强制转换为字符串。来自规范:
Input Coercion
When expected as an input type, any string (such as "4"
) or integer (such as 4
) input value should be coerced to ID as appropriate for the ID formats a given GraphQL server expects. Any other input value, including float input values (such as 4.0
), must raise a query error indicating an incorrect type.
这让我解决了最初的问题。
我有一个 mysql 后端,我的 PK 是整数。
依我看,我有以下选择:
- 开始使用 UUID 进行 PK。但是,这有 performance implications.
- 忽略在整个应用程序中具有唯一 ID 的隐式要求(源自 relayjs 生态系统),并尽可能将 ID 转换为数字以供内部使用。
Hash 在应用程序数据层对 ID 进行编码,例如UUID base64
来自 table 名称和 PK 值的串联。
我选择后一个选项。这也是graphql-relay-js
has adopted via toGlobalId
and fromGlobalId
.
的做法
不清楚什么时候使用GraphQLID
instead of GraphQLInt
。
考虑以下架构:
type User {
id: Int!
firstName: String!
lastName: String!
}
type Query {
user (id: ID!): User
}
在Query.user
的情况下,使用GraphQLID
还是GraphQLInt
似乎没有区别。
在 User.id
的情况下,使用 GraphQLID
会将输入转换为字符串。使用 GraphQLInt
将确保输入为整数。
这使得查询和类型系统不一致。
graphql-js spec 简单地说:
A
GraphQLScalarType
that represents an ID.
这是一个实现细节吗(例如,GraphQL 客户端应该尽可能将 GraphQLID
转换为整数),还是期望 ID
始终是 graphql 中的字符串?
我查看了 GraphQL 规范。
The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a
String
; however, it is not intended to be human‐readable. While it is often numeric, it should always serialize as aString
.
– https://spec.graphql.org/April2016/#sec-ID
这回答了它是留给实现还是由规范规定的问题,即 ID 应始终序列化为 String
。
此外,在输入类型的上下文中,需要将输入强制转换为字符串。来自规范:
Input Coercion
When expected as an input type, any string (such as
"4"
) or integer (such as4
) input value should be coerced to ID as appropriate for the ID formats a given GraphQL server expects. Any other input value, including float input values (such as4.0
), must raise a query error indicating an incorrect type.
这让我解决了最初的问题。
我有一个 mysql 后端,我的 PK 是整数。
依我看,我有以下选择:
- 开始使用 UUID 进行 PK。但是,这有 performance implications.
- 忽略在整个应用程序中具有唯一 ID 的隐式要求(源自 relayjs 生态系统),并尽可能将 ID 转换为数字以供内部使用。
Hash在应用程序数据层对 ID 进行编码,例如UUIDbase64
来自 table 名称和 PK 值的串联。
我选择后一个选项。这也是graphql-relay-js
has adopted via toGlobalId
and fromGlobalId
.