运行 GraphQL 查询返回 ID `1` 的格式无效

问题描述

在热巧克力研讨会之后,在第 4 步之后,运行查询

query GetSpecificSpeakerById {
  a: speakerById(id: 1) {
    name
  }
  b: speakerById(id: 1) {
    name
  }
}

我收到以下错误

The ID `1` has an invalid format.

此外,对于所有以 ID 作为参数的查询都会抛出相同的错误,也许这可能是一个提示,要检查什么,对我来说,一个刚刚运行研讨会的人仍然不清楚。

基于(未接受)类似问题 Error "The ID `1` has an invalid format" when querying HotChocolate 中的回答,我检查了 Relay 及其配置并且看起来不错。

DI

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(CreateAutomapper());
    services.AddPooledDbContextFactory<ApplicationDbContext>(options => 
        options.Usesqlite(CONNECTION_STRING).UseLoggerFactory(ApplicationDbContext.DbContextLoggerFactory));
    services
        .AddGraphQLServer()
        .AddQueryType(d => d.Name(Consts.QUERY))
            .AddTypeExtension<SpeakerQueries>()
            .AddTypeExtension<SessionQueries>()
            .AddTypeExtension<TrackQueries>()
        .AddMutationType(d => d.Name(Consts.MUTATION))
            .AddTypeExtension<SpeakerMutations>()
            .AddTypeExtension<SessionMutations>()
            .AddTypeExtension<TrackMutations>()
        .AddType<AttendeeType>()
        .AddType<SessionType>()
        .AddType<SpeakerType>()
        .AddType<TrackType>()
        .EnableRelaySupport()
        .AddDataLoader<SpeakerByIdDataLoader>()
        .AddDataLoader<SessionByIdDataLoader>();
}

扬声器类型

public class SpeakerType : ObjectType<Speaker>
{
    protected override void Configure(IObjectTypeDescriptor<Speaker> descriptor)
    {
        descriptor
            .ImplementsNode()
            .IdField(p => p.Id)
            .ResolveNode(WithDataLoader);
    }

    // implementation
}

查询自身

[ExtendobjectType(Name = Consts.QUERY)]
public class SpeakerQueries
{
    public Task<Speaker> GetSpeakerByIdAsync(
        [ID(nameof(Speaker))] int id,SpeakerByIdDataLoader DataLoader,CancellationToken cancellationToken) => DataLoader.LoadAsync(id,cancellationToken);
}

但没有一点运气。还有什么其他的,我可以检查什么?完整的项目是 available on my GitHub

解决方法

我看到你在这个项目上启用了中继支持。 端点执行有效的中继 ID。

Relay 向客户端公开不透明的 ID。你可以在这里读更多关于它的内容: https://graphql.org/learn/global-object-identification/

简而言之,中继 ID 是类型名称和 ID 的 base64 编码组合。

要在浏览器中进行编码或解码,您只需在控制台上使用 atobbtoa

所以 id "U3BlYWtlcgppMQ==" 包含值

"Speaker
i1"

您可以在浏览器中使用 btoa("U3BlYWtlcgppMQ==") 解码此值并使用

对字符串进行编码
atob("Speaker
i1")

所以这个查询将起作用:

query GetSpecificSpeakerById {
  a: speakerById(id: "U3BlYWtlcgppMQ==") {
    id
    name
  } 
}