图身份
此技术笔记的目的是演示用于识别试图使用图的参与者的查询/更新。
此技术笔记的目的是演示查询/更新更新以识别试图使用图的参与者。以下示例可以启发如何在一个GraphQL模式中描述参与者身份,并包含用户和服务器的多个用例。
我们的用例识别了经过身份验证的用户和服务以及匿名用户。
首先,我们为查询和更新身份类型定义接口。
interface Identity {"An ID we can use to identify the session."id: ID!}interface MutableIdentity {"An ID we can use to identify the session."id: ID!}
然后我们为我们认证和不认证的标识创建接口的具体类型。
type AnonymousIdentity implements Identity @key(fields: "id") {"An ID we can use to identify the session."id: ID!}type UserIdentity implements Identity @key(fields: "id") {"An ID we can use to identify the session."id: ID!"A reference to the authenticated user entity."user: User}type ServiceIdentity implements Identity @key(fields: "id") {"An ID we can use to identify the session."id: ID!"A reference to the authenticated service entity."service: Service}
以及一个认证错误响应。
type NotAuthenticatedError {message: String}
接下来,我们将构造我们的 查询类型和响应联合体。在此我们选择了联合体,以便我们能够返回身份和错误作为响应数据。
可空性变得非常重要;可空性如何影响客户端处理失败的方式存在细微差别。
union AuthIdentity = UserIdentity | ServiceIdentity | NotAuthenticatedErrorunion CurrentUser = UserIdentity | AnonymousIdentitytype Query {"A query which returns an authenticated user or service, or an anonymous identity."session: Identity!"A query which returns the currently authenticated identity or an error."whoami: AuthIdentity!"A query which returns the currently authenticated user identity, or an anonymous identity."me: CurrentUser!}
⚠️ 小心
在前面的示例中,所有的 查询响应类型都不是可空的,这意味着如果服务器无法提供某种身份,则请求将失败。或者,我们也可以允许可空的响应,这些响应可以用来表示匿名或不认证的使用案例。
此外,通过在响应联合体中提供NotAuthenticatedError,我们可以在客户端应用程序中通知何时为用户提供特定体验。
然后通过分离 突变和 查询身份,我们能够分离:
- 可以在身份上执行的操作。
- 可以查询的身份。
type MutableAnonymousIdentity implements MutableIdentity @key(fields: "id") {id: ID!authenticateWithEmailAndPassword(credentials: EmailAndPasswordCredentials!): UserIdentity!}type MutableUserIdentity implements MutableIdentity @key(fields: "id") {id: ID!resetPassword(credentials: ResetPasswordCredentials!): UserIdentity!}type MutableServiceIdentity implements MutableIdentity @key(fields: "id") {id: ID!service: MutableService!}union MutableCurrentUser = MutableUserIdentity | NotAuthenticatedErrortype Mutation {session: MutableIdentity!me: MutableCurrentUser!}
最后,使用先前定义的模式执行 操作将如下所示。
query CurrentAuth {session {id}whoami {id}me {id}}mutation Login($credentials: EmailAndPasswordCredentials!) {session {... on MutableAnonymousIdentity {authenticateWithEmailAndPassword(credentials: $credentials) {user {...}}}}}mutation ResetPassword($credentials: ResetPasswordCredentials!) {me {... on MutableUserIdentity {resetPassword(credentials: $credentials) {user {...}}}}}