0

I am trying to copy this GraphQL schema (don't have access to its code): TargetSchema

type User {
  id: ID!
  email: String!
  role: UserRole!
}

type ForbiddenError {
  message: String!
}

type Mutation {
  login(input: LoginInput!): LoginOutput!
}

union LoginOutput = User | ForbiddenError

The frontend makes this request (and it cannot be modified):

mutation login{
  login(input:{usernameOrEmail:"user@example.com",password:"qwerty123"})
{
  ...on User{__typename id email role }
  ...on ForbiddenError{__typename message}
  }
}

I tried to create an interface that two objects, User and ForbiddenError, would share,

[UnionType("LoginOutput")]
public interface ILoginOutput
{
}
public class ForbiddenError : ILoginOutput
{
    public string Message { get; set; }
}
public class User : ILoginOutput
{
    public string Id { get; set; }
    
    public string Email { get; set; }

    public string Role { get; set; }
}
public ILoginOutput Login(
    string usernameOrEmail,
    string password,
    [Service] IHttpContextAccessor httpContextAccessor)
{
    <...>
    if (...)
    {
        return new ForbiddenError();
    }

    <...>
    return user;
}

but in this case, I end up with the following schema: UnionSchema And error in request:

Fragment cannot be spread here as objects of type "LoginPayload" can never be of type "User".

I tried to solve the problem by using an exception,

public class ForbiddenError : Exception
{
}
[Error<ForbiddenError>]
public User Login(
    string usernameOrEmail,
    string password,
    [Service] IHttpContextAccessor httpContextAccessor)
{
     <...>
}

but I ended up with the following schema Exception And same error in request:

Fragment cannot be spread here as objects of type "LoginPayload" can never be of type "User".

How can I get the schema like the one in the first image? So that the specified query to GraphQL can be executed.

motpfofs
  • 103
  • 1
  • 2
  • 4
  • I don't speak GraphQL. But mimicking a `C` language union in C# is done by using a `struct` with `LayoutKind.Explicit` – Flydog57 Jul 22 '23 at 00:57

0 Answers0