Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a GraphQL input type inherit from another type or interface?

Tags:

graphql

Is it possible to use inheritance with GraphQL input types?

Something like that (this, of course, doesn't work with input types):

interface UserInputInterface {
  firstName: String
  lastName: String
}

input UserInput implements UserInputInterface {
  password: String!
}

input UserChangesInput implements UserInputInterface {
  id: ID!
  password: String
}
like image 477
kyrisu Avatar asked Jan 29 '17 12:01

kyrisu


People also ask

Does GraphQL support inheritance?

GraphQL does not inherently support inheritance. There is no syntax that would help you avoid duplication of fields across multiple types. Barring that, you can also utilize a library like graphql-s2s which allows you to utilize inheritance and generic types.

Can an interface implement another interface GraphQL?

An interface cannot implement another interface.

What other types can be used in a GraphQL schema?

The GraphQL schema language supports the scalar types of String , Int , Float , Boolean , and ID , so you can use these directly in the schema you pass to buildSchema . By default, every type is nullable - it's legitimate to return null as any of the scalar types.

Does GraphQL support union types?

The GraphQL type system also supports Unions . Unions are identical to interfaces, except that they don't define a common set of fields. Unions are generally preferred over interfaces when the possible types do not share a logical hierarchy.


3 Answers

No, the spec does not allow input types to implement interfaces. And GraphQL type system in general does not define any form of inheritance (the extends keyword adds fields to an existing type, and isn't for inheritance). The spec is intentionally constrained to stay simple. This means that you're stuck repeating fields across input types.

That said, depending on the way you construct your schema, you could build some kind of type transformer that appends the common fields programmatically based on some meta-data, e.g. a directive.

Better yet, you might be able to solve your problem via composition (always keep composition over inheritance in mind). E.g.

input Name {
  firstName: String
  lastName: String
}

input UserInput {
  name: Name
  password: String!
}

input UserChangesInput {
  name: Name
  id: ID!
  password: String
}

The client now has to send an object a level deeper, but that doesn't sound like much of a price for avoiding big repeating chunks. It might actually be good for the client as well, as they can now have common logic for building names, regardless of the query/mutation using them.

In this example, where it's only 2 simple fields, this approach is an overkill, but in general - I'd say it's the way to go.

like image 162
kaqqao Avatar answered Oct 10 '22 12:10

kaqqao


Starting with the June2018 stable version of the GraphQL spec, an Input Object type can extend another Input Object type:

Input object type extensions are used to represent an input object type which has been extended from some original input object type.

This isn't inheritance per se; you can only extend the base type, not create new types based on it:

extend input MyInput {
  NewField: String
}

Note there is no name for the new type; the existing MyInput type is extended.

The JavaScript reference implementation has implemented Input Object extensions in GraphQL.js v14 (June 2018), though it's unclear how to actually pass the extended input fields to a query without getting an error.

For actual type inheritance, see the graphql-s2s library.

like image 15
Dan Dascalescu Avatar answered Oct 10 '22 11:10

Dan Dascalescu


It's doable using a custom directive.

Code Summary

const typeDefs = gql`
  directive @inherits(type: String!) on OBJECT

  type Car {
    manufacturer: String
    color: String
  }
  
  type Tesla @inherits(type: "Car") {
    manufacturer: String
    papa: String
    model: String
  }
  
  type Query {
    tesla: Tesla
  }
`;

const resolvers = {
    Query: {
        tesla: () => ({ model: 'S' }),
    },
    Car: {
        manufacturer: () => 'Ford',
        color: () => 'Orange',
    },
    Tesla: {
        manufacturer: () => 'Tesla, Inc',
        papa: () => 'Elon',
    },
};

class InheritsDirective extends SchemaDirectiveVisitor {
    visitObject(type) {
        const fields = type.getFields();
        const baseType = this.schema.getTypeMap()[this.args.type];
        Object.entries(baseType.getFields()).forEach(([name, field]) => {
            if (fields[name] === undefined) {
                fields[name] = { ...field };
            }
        });
    }
}

const schemaDirectives = {
    inherits: InheritsDirective,
};

Query:

query {
  tesla {
    manufacturer
    papa
    color
    model
  }
}

Output:

{
  "data": {
    "tesla": {
      "manufacturer": "Tesla, Inc",
      "papa": "Elon",
      "color": "Orange",
      "model": "S",
    }
  }
}

Working example at https://github.com/jeanbmar/graphql-inherits.

like image 3
Jean-Baptiste Martin Avatar answered Oct 10 '22 12:10

Jean-Baptiste Martin