Skip to content

Pass context into scalar coercing #1893

Closed

Description

@vojtapol

Making scalar coercion more powerful

It would be a huge advantage to be able to access the context during serializing/deserializing scalars. It would allow to reduce a lot of additional type conversion that must happen in data fetchers on input and output because it requires some contextual information.

Use cases:

Converting date time to client's time zone

Some applications need to be aware of the current user time zone. This is for example necessary when aggregating calendar events into dates. It just cannot be done in UTC.

The application could internally work with java.time.Instant. During the conversion from the literal to Java type the context object could provide the current client time-zone and convert it to the correct Instant thus keeping the conversion logic in one place.

GraphQLScalarType
    .newScalar()
    .name("DateTime")
    .coercing(new Coercing<Instant, String>() {
        @Override
        public String serialize(Object instant, Context context) {
            if (instant instanceof Instant) {
                ((Instant) instant).atZone(context.getZoneId()).toString();
            }
            // throw
        }
        @Override
        public Instant parseValue(Object input, Context context) {
            LocalDateTime.parse(input).atZone(context.getZoneId).toInstant();
        }
    })
    .build();

Translating strings into client's locale

Similarly, Strings could be translated on output by using a special type internally MessageBundleKey and converting it to GraphQL string in the coercion. By being able to access the context it would be possible to determine the client locale and translate the message bundle key type into GraphQL string in the correct language.

GraphQLScalarType
    .newScalar()
    .name("LocalizedString")
    .coercing(new Coercing<MessageBundleKey, String>() {
        @Override
        public String serialize(Object key, Context context) {
            return messageBundle.getMessage(key, context.getLocale());
        }
    })
    .build();

Workaround

The only current workaround is to inject the context in a different way. For example using thread local global variables. Spring already offers a similar mechanism using the LocaleContextHolder class. The disadvantage is that it relies on the fact that each thread has a separate context which is not true in a reactive app or when using subscriptions.

Activity

  1. glasser commented on May 20, 2020

    @glasser
    Contributor

    This would be helpful here too. Right now we construct our entire GraphQLSchema in a way that injections some dependencies when we create it, but it would simpler if we could just construct it once and reuse it in tests without needing to make a whole new GraphQLSchema just to inject, eg, a fake clock into a scalar parseLiteral.

  2. bbakerman commented on May 23, 2020

    @bbakerman
    Member

    I agree with this sentiment - the Coercing is a SPI and like the DataFetcher SPI you need context for more extended cases.

    The original code was based on the graphql-js implementation and simple String/Int scalars do not need it. But as you say a DateTime based on the current callers Locale needs context.

    The trick here would be migration to this. All the Scalars existing today do not expect a context (we would probably call it ScalarEnvironment to ape DataFetchingEnvironment) and hence that MUST continue

    That said we already have a example where we have done this

    graphql.schema.Coercing#parseLiteral(java.lang.Object, java.util.Map<java.lang.String,java.lang.Object>)

    which is defaulted on the interface. We would need to do the same

  3. bbakerman commented on May 23, 2020

    @bbakerman
    Member

    Looking into this it gets a little tricky in terms of what "context" is available.

    For example `graphql.schema.Coercing#serialize`` is only ever called during query execution phase and hence all the good stuff is available to it.

    However graphql.schema.Coercing#parseValue and graphql.schema.Coercing#parseLiteral(java.lang.Object, java.util.Map<java.lang.String,java.lang.Object>) are called in a number of places where there is not runtime execution context (or the context is not currently send to them).

    For example the SDL generation code uses parseLiteral to interpret inline argument defaults and so on.

    I say this only to outline its a little tricky - we might have the situaton where context can be null for a subset of the Coercing calls.

    This leads me to imagine a "CoercingSerialiseEnvironmentand aCoercingParseLiteralEnvironment` and so on

  4. vojtapol commented on May 24, 2020

    @vojtapol
    Author

    I am not sure I understand what is the current use case of graphql.schema.Coercing#parseLiteral(java.lang.Object, java.util.Map<java.lang.String,java.lang.Object>) but yes, adding default methods to the interface that take something like ScalarEnvironment would work great for us and keep it backwards compatible. Assuming that the ScalarEnvironment contains our custom context object.

  5. dondonz commented on Aug 19, 2022

    @dondonz
    Member

    Resurrecting this old thread to say, coercion context coming in #2912

  6. bbakerman commented on Aug 20, 2022

    @bbakerman
    Member

    Lets leave this open UNTIL we merge that PR - its likely but not yet done

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions