如何让HotChocolate用key指令来装饰对象类型?

问题描述 投票:0回答:1

给定对象:

public class Parent
{
    public Parent(string id, string name)
    {
        Id = id;
        Name = name;
    }

    [Key]
    [ID]
    public string Id { get; }

    public string Name { get; }

    [ReferenceResolver]
    public static Parent? Get(ParentRepository repository, string id)
    {
        return repository.GetParent(id);
    }
}

我得到以下 graphql 模式:

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

但是期待这个:

type Parent @key(fields: "id") {
  id: ID!
  name: String!
}

引导代码:

builder.Services.AddGraphQLServer()
    .AddQueryType<Query>()
    .RegisterService<ParentRepository>()
    .AddApolloFederation();

套餐版本:

<PackageReference Include="HotChocolate.ApolloFederation" Version="13.9.12" />
<PackageReference Include="HotChocolate.AspNetCore" Version="13.9.12" />
graphql hotchocolate graphql-federation
1个回答
0
投票

要使用 @key 指令输出架构,您可以按照 这些说明HotChocolate.AspNetCore.CommandLine 包添加到项目中。

一定要替换app.Run():

//app.Run();

await app.RunWithGraphQLCommandsAsync(args);

然后您可以通过传入

schema export
命令行选项来执行应用程序。

例如,从代码运行时:

dotnet run -- schema export

瞧,输出包含 @key 指令!

schema @link(url: "https:\/\/specs.apollo.dev\/federation\/v2.6", import: [ "@key", "@tag", "FieldSet" ]) {
  query: Query
}

type Parent @key(fields: "id") {
  id: ID!
  name: String!
}

type Query {
  allParents: [Parent!]!
  _service: _Service!
  _entities(representations: [_Any!]!): [_Entity]!
}

"This type provides a field named sdl: String! which exposes the SDL of the service's schema. This SDL (schema definition language) is a printed version of the service's schema including the annotations of federation directives. This SDL does not include the additions of the federation spec."
type _Service {
  sdl: String!
}

"Union of all types that key directive applied. This information is needed by the Apollo federation gateway."
union _Entity = Parent

"Used to indicate a combination of fields that can be used to uniquely identify and fetch an object or interface."
directive @key(fields: FieldSet! resolvable: Boolean = true) repeatable on OBJECT | INTERFACE

"Links definitions within the document to external schemas."
directive @link("Gets imported specification url." url: String! "Gets optional list of imported element names." import: [String!]) repeatable on SCHEMA

"Scalar representing a set of fields."
scalar FieldSet

"The _Any scalar is used to pass representations of entities from external services into the root _entities field for execution. Validation of the _Any scalar is done by matching the __typename and @external fields defined in the schema."
scalar _Any
© www.soinside.com 2019 - 2024. All rights reserved.