Skip to content

[Issue] Introduced support of custom scalar types for GraphQL schema #36877

Closed
@m2-assistant

Description

@m2-assistant

This issue is automatically created based on existing pull request: #34651: Introduced support of custom scalar types for GraphQL schema


Support for GraphQL custom scalars

This PR adds support for custom scalar types to GraphQL.

https://graphql.org/learn/schema/#scalar-types
https://webonyx.github.io/graphql-php/type-definitions/scalars/#writing-custom-scalar-types

After PR is merged a developer will be able to define custom scalar types and implementations by using Magento schema.

For example, the following declaration enables Json scalar type

scalar Json
@implementation(class: "Magento\\MyModule\\Model\\JsonScalarType")
@doc(description:"Json type")
{}

Scalar type implementation should implement new Magento\Framework\GraphQl\Schema\Type\Scalar\CustomScalarInterface

Something like:

class JsonScalarType implements \Magento\Framework\GraphQl\Schema\Type\Scalar\CustomScalarInterface
{

    public function serialize($value)
    {
        return json_decode($value);
    }

    public function parseValue($value)
    {
        return json_encode($value);
    }

    public function parseLiteral($valueNode, ?array $variables = null)
    {
        return $valueNode->value;
    }
}

For example, a query that accepts JSON as input and returns JSON as output and has a resolver that returns you an argument that you just passed then you will see a picture similar to this:

Screenshot from 2021-11-16 16-41-42

This feature could be widely useful to express values that may have validation, like HTML, emails, URLs, dates, etc., and for more advanced cases like EAV attributes, where value can be expressed as a single scalar or array of scalars.

Contribution checklist (*)

  • Pull request has a meaningful description of its purpose
  • All commits are accompanied by meaningful commit messages
  • All new or changed code is covered with unit/integration tests (if applicable)
  • README.md files for modified modules are updated and included in the pull request if any README.md predefined sections require an update
  • All automated tests passed successfully (all builds are green)

Metadata

Metadata

Assignees

Labels

Area: FrameworkComponent: GraphQLGraphQLComponent: GraphQlSchemaStitchingIssue: ConfirmedGate 3 Passed. Manual verification of the issue completed. Issue is confirmedPriority: P1Once P0 defects have been fixed, a defect having this priority is the next candidate for fixing.Progress: doneReported on 2.4.xIndicates original Magento version for the Issue report.Reproduced on 2.4.xThe issue has been reproduced on latest 2.4-develop branch

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions