Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include directives in SchemaPrinter output #552

Open
franzwilding opened this issue Oct 7, 2019 · 18 comments
Open

Include directives in SchemaPrinter output #552

franzwilding opened this issue Oct 7, 2019 · 18 comments

Comments

@franzwilding
Copy link

Hey!

I'm currently playing around with a custom schema builder, that allows registering classes that extend the schema and eventually create a cacheable DocumentNode. It is working pretty well, my current solution looks like this:

    /**
     * @return DocumentNode
     * @throws \GraphQL\Error\Error
     * @throws \GraphQL\Error\SyntaxError
     */
    public function buildCacheableSchema() : DocumentNode {

        $schema = BuildSchema::build(self::BASE_SCHEMA);

        foreach($this->extenders as $extender) {
            if($extension = $extender->extend($schema)) {
                $schema = SchemaExtender::extend($schema, Parser::parse($extender->extend($schema)));
            }
        }

        return Parser::parse(SchemaPrinter::doPrint($schema));
    }

However, I am facing the problem, that custom directives get lost during doPrint, because of the implementation of SchemaPrinter::printField which only includes deprecated directive .

Now my question consists of two parts:

  1. Is there a better solution to get the DocumentNode from a Schema, besides doing parse(doPrint(schema))?

  2. And if this actually is the best solution to do this, how do I get my custom directives into the final schema?

Thank you!

@vladar
Copy link
Member

vladar commented Oct 13, 2019

This topic is a bit controversial. See graphql/graphql-js#2020 for some details. We will adopt the same solution as graphql-js eventually. So I will keep this issue open until it is resolved in the reference implementation.

@renepardon
Copy link

renepardon commented Nov 25, 2019

Hello,

I build the federation implementation into lighthouse right now. nuwave/lighthouse#1051

The problem I'm facing here is that I also need custom directives printed into the Schema (For the _service { sdl } request and we wouldn't like to implement this through a custom printer into lighthouse, because for this to work we would need to overwrite/duplicate a lot of code from webonyx/graphql-php. Reference request is #515 which is already closed but this issue (#552) looks promising that we could do it easier.

What do you suggest on how to continue?

@spawnia
@vladar

@obi1kenobi
Copy link

I believe graphql/graphql-js#2389 is the directly-equivalent issue of this one. Hoping GraphQL.js can address it soon so all the ports can follow suit!

@spawnia
Copy link
Collaborator

spawnia commented Jun 9, 2020

@vladar I agree to wait what the reference implementation does for an official solution.

We might still unblock users who currently wish to extend the SchemaPrinter by making its private methods protected. If we don't put the @api PHPDoc annotation, we don't overcommit to keeping them stable, but still allow an escape hatch.

@vladar
Copy link
Member

vladar commented Jun 9, 2020

Agree here. A PR for this is surely welcome!

spawnia added a commit that referenced this issue Jun 11, 2020
This opens up a much needed escape hatch for experimental features
such as Apollo Federation, see #552
vladar pushed a commit that referenced this issue Jun 19, 2020
This opens up a much needed escape hatch for experimental features
such as Apollo Federation, see #552
@fabis94
Copy link
Contributor

fabis94 commented Dec 3, 2020

What was the point of making all methods protected, if they all still refer to eachother with self:: not static::? Half of the entire class must be copy-pasted to the child type just to override a single method.

@spawnia
Copy link
Collaborator

spawnia commented Dec 3, 2020

@fabis94 instead of complaining, you can do something about it and create a PR.

@fabis94
Copy link
Contributor

fabis94 commented Dec 3, 2020

here it is - #747

@spawnia spawnia changed the title Custom directives get lost during schema printing Include directives in SchemaPrinter output Dec 25, 2020
@spawnia
Copy link
Collaborator

spawnia commented Jun 23, 2021

We have been using an extensible version of the SchemaPrinter to add federation support for https://github.com/nuwave/lighthouse. See https://github.com/nuwave/lighthouse/blob/master/src/Federation/SchemaPrinter.php for the implementation. Basically, it adds a config option printDirectives that takes a function with the following signature:

(Type|EnumValueDefinition|FieldArgument|FieldDefinition|InputObjectField $definition): string

It is called whenever one of the relevant definitions is encountered and may print any directives. Here is a concrete implementation for the purposes of federation support: https://github.com/nuwave/lighthouse/blob/0d8f0fb8a3dd2791dda4c772f3db4b53ee072fb3/src/Federation/FederationPrinter.php#L81

@spawnia
Copy link
Collaborator

spawnia commented Nov 5, 2021

I added a PR to the reference implementation to gauge their interest and avoid a diverging implementation: graphql/graphql-js#3362

@LastDragon-ru
Copy link
Contributor

LastDragon-ru commented Feb 5, 2022

After PR #996, I've realized that it will never be merged I need something more:

  1. Removing unused types from the schema (probably related to Exclude unused standard types from the schema #964) - we have a lot of custom directives that change schema by adding new queries/directives and tests for them. One of the problems is that Lighthouse includes some types that are also included in the schema but never used. These unused types make a comparison of generated schema a bit difficult and annoying.

  2. Proposed PR doesn't allow print custom Lighthouse directives and it is not possible to solve (seems there is no way to add directives to Types. or maybe I've missed something?). But we need some of them.

  3. Default Printer add spaces for empty lines in description and they make editing is difficult (for me; because of "remove trailing spaces" ide setting)

    image

  4. I want 4 spaces instead of 2 😅

  5. Other formatting issues that are difficult/impossible to solve eg proper line length calculation, or sorting (normalization) the fields/etc to the easy comparison.

So I've created a new SchemaPrinter 😁 Because point (2) it is required Lighthouse to work, but if (2) can be solved it is, technically, can be converted into a universal printer.

Right now it is probably a bit experimental, so any feedback is really appreciated. It is available since v0.11.0 of my package (that also provides alternative for @whereConditions/@orderBy).

As I mention in PR we need to print directives to provide documentation, but graphql-playground is not supported custom directives yet (graphql/graphql-playground#1207) 😞 So I've also added printDirectivesInDescription setting that allows include directives in the description.

Other known/related issues:

Usage is very simple (please see code & tests for more examples):

<?php declare(strict_types = 1);

namespace LastDragon_ru\LaraASP\GraphQL\SchemaPrinter;

use GraphQL\Type\Schema;
use LastDragon_ru\LaraASP\GraphQL\SchemaPrinter\Contracts\Printer;
use LastDragon_ru\LaraASP\GraphQL\SchemaPrinter\Settings\DefaultSettings;

$settings = new DefaultSettings();
$printer  = $this->app->make(Printer::class)->setSettings($settings);
$schema   = new Schema([]);
$actual   = $printer->print($schema);

// $actual->getUnusedTypes();

echo (string) $actual;
Introspection schema
"""
A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.
"""
enum __DirectiveLocation {
    """
    Location adjacent to an argument definition.
    """
    ARGUMENT_DEFINITION

    """
    Location adjacent to an enum definition.
    """
    ENUM

    """
    Location adjacent to an enum value definition.
    """
    ENUM_VALUE

    """
    Location adjacent to a field.
    """
    FIELD

    """
    Location adjacent to a field definition.
    """
    FIELD_DEFINITION

    """
    Location adjacent to a fragment definition.
    """
    FRAGMENT_DEFINITION

    """
    Location adjacent to a fragment spread.
    """
    FRAGMENT_SPREAD

    """
    Location adjacent to an inline fragment.
    """
    INLINE_FRAGMENT

    """
    Location adjacent to an input object field definition.
    """
    INPUT_FIELD_DEFINITION

    """
    Location adjacent to an input object type definition.
    """
    INPUT_OBJECT

    """
    Location adjacent to an interface definition.
    """
    INTERFACE

    """
    Location adjacent to a mutation operation.
    """
    MUTATION

    """
    Location adjacent to an object type definition.
    """
    OBJECT

    """
    Location adjacent to a query operation.
    """
    QUERY

    """
    Location adjacent to a scalar definition.
    """
    SCALAR

    """
    Location adjacent to a schema definition.
    """
    SCHEMA

    """
    Location adjacent to a subscription operation.
    """
    SUBSCRIPTION

    """
    Location adjacent to a union definition.
    """
    UNION

    """
    Location adjacent to a variable definition.
    """
    VARIABLE_DEFINITION
}

"""
An enum describing what kind of type a given `__Type` is.
"""
enum __TypeKind {
    """
    Indicates this type is an enum. `enumValues` is a valid field.
    """
    ENUM

    """
    Indicates this type is an input object. `inputFields` is a valid field.
    """
    INPUT_OBJECT

    """
    Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.
    """
    INTERFACE

    """
    Indicates this type is a list. `ofType` is a valid field.
    """
    LIST

    """
    Indicates this type is a non-null. `ofType` is a valid field.
    """
    NON_NULL

    """
    Indicates this type is an object. `fields` and `interfaces` are valid fields.
    """
    OBJECT

    """
    Indicates this type is a scalar.
    """
    SCALAR

    """
    Indicates this type is a union. `possibleTypes` is a valid field.
    """
    UNION
}

"""
A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.

In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.
"""
type __Directive {
    args: [__InputValue!]!
    description: String
    isRepeatable: Boolean!
    locations: [__DirectiveLocation!]!
    name: String!
}

"""
One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.
"""
type __EnumValue {
    deprecationReason: String
    description: String
    isDeprecated: Boolean!
    name: String!
}

"""
Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.
"""
type __Field {
    args: [__InputValue!]!
    deprecationReason: String
    description: String
    isDeprecated: Boolean!
    name: String!
    type: __Type!
}

"""
Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.
"""
type __InputValue {
    """
    A GraphQL-formatted string representing the default value for this input value.
    """
    defaultValue: String

    description: String
    name: String!
    type: __Type!
}

"""
A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.
"""
type __Schema {
    """
    A list of all directives supported by this server.
    """
    directives: [__Directive!]!

    """
    If this server supports mutation, the type that mutation operations will be rooted at.
    """
    mutationType: __Type

    """
    The type that query operations will be rooted at.
    """
    queryType: __Type!

    """
    If this server support subscription, the type that subscription operations will be rooted at.
    """
    subscriptionType: __Type

    """
    A list of all types supported by this server.
    """
    types: [__Type!]!
}

"""
The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.

Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.
"""
type __Type {
    description: String
    enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
    fields(includeDeprecated: Boolean = false): [__Field!]
    inputFields: [__InputValue!]
    interfaces: [__Type!]
    kind: __TypeKind!
    name: String
    ofType: __Type
    possibleTypes: [__Type!]
}

"""
Marks an element of a GraphQL schema as no longer supported.
"""
directive @deprecated(
    """
    Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).
    """
    reason: String = "No longer supported"
)
on
    | ENUM_VALUE
    | FIELD_DEFINITION

"""
Directs the executor to include this field or fragment only when the `if` argument is true.
"""
directive @include(
    """
    Included when true.
    """
    if: Boolean!
)
on
    | FIELD
    | FRAGMENT_SPREAD
    | INLINE_FRAGMENT

"""
Directs the executor to skip this field or fragment when the `if` argument is true.
"""
directive @skip(
    """
    Skipped when true.
    """
    if: Boolean!
)
on
    | FIELD
    | FRAGMENT_SPREAD
    | INLINE_FRAGMENT

@LastDragon-ru
Copy link
Contributor

@spawnia could you please take a look on https://github.com/LastDragon-ru/lara-asp/blob/5c20332d05223a8611c3cb0e5e9647d693b02453/packages/graphql/src/SchemaPrinter/Misc/DirectiveResolver.php#L61-L103 ? Maybe I've missed something and there is a better/propper way to include type definitions from Directive:definition() into the schema.

@spawnia
Copy link
Collaborator

spawnia commented Feb 27, 2022

@LastDragon-ru seems fine, I would probably do something similar in Lighthouse if we actually needed the definitions to be part of the schema.

@LastDragon-ru
Copy link
Contributor

@spawnia , thank you.

@LastDragon-ru
Copy link
Contributor

So I've created a new SchemaPrinter 😁

The SchemaPrinter with few PHPUnit assertions for Schema/Types comparison are finally available as a part of lara-asp package (Lighthouse is required). So if someone need directives maybe you can try to use SchemaPrinter.

@LastDragon-ru
Copy link
Contributor

The SchemaPrinter was extracted into a separate package graphql-printer and can be used without Laravel/Lighthouse 🎉 The v3 support graphql-php v14, upcoming v4 will require v15.

@LastDragon-ru
Copy link
Contributor

Since v4.4.0 the SchemaPrinter can print queries and any node :) (use Printer::printNode()).

@LastDragon-ru
Copy link
Contributor

LastDragon-ru commented Oct 27, 2023

Since v5.0.0 there are two new methods:

  • print() - print one type/node only
  • export() - print the type/node and all other types/nodes/directives which it use

Please see docs for more details 😸

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants