GraphQL: определение параметра Dynami c для запроса - PullRequest
0 голосов
/ 10 февраля 2020

Я занимаюсь разработкой веб-приложения с архитектурой микросервисов, где уровень пользовательского интерфейса представляет собой Asp. Net Core web app. Я добавил GraphQL пакет на уровень пользовательского интерфейса моего приложения и пытаюсь запросить его со стороны клиента. У меня такая ситуация впереди:

Запрос на стороне клиента выглядит следующим образом:

query OwnerQuery($ownerId:ID!)
{
  owner(ownerId:$ownerId){
    id,
    name,
    address,
    accounts
    {
      id,
      type,
      ownerId,
      description
    }
  }
}

с предоставленным значением для $ownerId, как показано ниже:

{
  "ownerId":"e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02"
}

и сервер ответит мне следующим результатом:

{
  "data": {
    "owner": {
      "id": "e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02",
      "name": "Milad",
      "address": "Tehran",
      "accounts": [
        {
          "id": "145cc51d-b80c-4d93-9319-8b2b7a0a2446",
          "type": "CASH",
          "ownerId": "e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02",
          "description": "Desc1"
        },
        {
          "id": "3fe6fe19-098c-4683-834a-a631265865f8",
          "type": "SAVINGS",
          "ownerId": "e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02",
          "description": "Desc2"
        },
        {
          "id": "7fed8d81-d9a5-40c7-bbeb-ca31f8247436",
          "type": "EXPENSE",
          "ownerId": "e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02",
          "description": "Desc3"
        },
        {
          "id": "07fdd2bb-0e70-4763-b56d-ff31bb895a7c",
          "type": "INCOME",
          "ownerId": "e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02",
          "description": "Desc4"
        }
      ]
    }
  }
} 

и на стороне сервера я настроил свой класс AppQuery, как показано ниже:

public class AppQuery : ObjectGraphType
{
    public AppQuery(IOwnerRepository repository)
    {
        Field<ListGraphType<OwnerType>>(
           "owners",
           resolve: context => repository.GetAll()
       );

        Field<OwnerType>(
            "owner",
            arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "ownerId" }),
            resolve: context =>
            {
                Guid id;
                if (!Guid.TryParse(context.GetArgument<string>("ownerId"), out id))
                {
                    context.Errors.Add(new ExecutionError("Wrong value for guid"));
                    return null;
                }

                return repository.GetById(id);
            }
        );
    }
}


Проблема:
Я хочу знать, возможно ли динамически определять новый параметр в запросе и как я могу обработать его на стороне сервера. Примерно так:

query OwnerQuery($ownerId:ID!, $ownerName:String!)
{
  owner(ownerId:$ownerId, ownerName:$ownerName){
    id,
    name,
    address,
    accounts
    {
      id,
      type,
      ownerId,
      description
    }
  }
}

с этими двумя значениями параметров:

{
  "ownerId":"e0aaf2ce-ce9d-40bb-abaf-2dfdb400bc02",
  "ownerName": "Milad"
}

Конечно, без изменения запроса на стороне сервера, подобного этому, для настройки нового параметра ownerName

public class AppQuery : ObjectGraphType
{
    public AppQuery(IOwnerRepository repository)
    {
        Field<ListGraphType<OwnerType>>(
           "owners",
           resolve: context => repository.GetAll()
       );

        Field<OwnerType>(
            "owner",
            arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "ownerId" },
                new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "ownerName" }),
            resolve: context =>
            {
                Guid id;
                if (!Guid.TryParse(context.GetArgument<string>("ownerId"), out id))
                {
                    context.Errors.Add(new ExecutionError("Wrong value for guid"));
                    return null;
                }

                string name = context.GetArgument<string>("ownerName");
                return repository.GetByIdAndName(id, name);
            }
        );
    }
}


Дополнительная информация:
Также для дополнительных пояснений я должен сказать, что я установил эти пакеты в свой проект:

<ItemGroup>
    <PackageReference Include="GraphQL" Version="2.4.0" />
    <PackageReference Include="GraphQL.Server.Transports.AspNetCore" Version="3.4.0" />
    <PackageReference Include="GraphQL.Server.Ui.Playground" Version="3.4.0" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
        <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
        <PrivateAssets>all</PrivateAssets>
    </PackageReference>
</ItemGroup>
...