Skip to content

graphql-java/graphql-java-extended-scalars

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Extended Scalars for graphql-java

Build Status Latest Release Latest Snapshot MIT licensed

Overview

This library provides extended scalars for graphql-java

GraphQL Scalars are the primitive leaf values in the GraphQL type system which cannot be queried further via sub-field selections.

The GraphQL Specification defines String, Int, Float, Boolean and ID as well-defined built-in scalars that must be present in a graphql type system. Beyond these, it is up to an implementation to decide what custom scalars are present.

You would use custom scalars when you want to describe more meaningful behavior or ranges of values.

Getting started

How to install

To use this library put the following into your gradle config

implementation 'com.graphql-java:graphql-java-extended-scalars:22.0'

or the following into your Maven config

<dependency>
  <groupId>com.graphql-java</groupId>
  <artifactId>graphql-java-extended-scalars</artifactId>
  <version>22.0</version>
</dependency>

Note:

use 22.0 or above for graphql-java 22.x and above

use 21.0 for graphql-java 21.x

use 20.2 for graphql-java 20.x

How to use extended scalars

Direct use

Register the scalar with graphql-java

RuntimeWiring.newRuntimeWiring().scalar(ExtendedScalars.DateTime)

Spring for GraphQL

If you are using Spring for GraphQL, register the scalar with RuntimeWiringConfigurer

@Configuration
public class GraphQlConfig {
    @Bean
    public RuntimeWiringConfigurer runtimeWiringConfigurer() {
        return wiringBuilder -> wiringBuilder.scalar(ExtendedScalars.DateTime);
    }
}

Netflix DGS

Note: Netflix also wraps this library in com.netflix.graphql.dgs:graphql-dgs-extended-scalars for automatic registration.

If you are using Netflix DGS, please see the following docs:

How to add extended scalars to your schema

The GraphQL Specification recommends the use of the @specifiedBy built-in schema directive to provide a scalar specification URL for specifying the behavior of custom scalar types.

directive @specifiedBy(url: String!) on SCALAR

To use a extended scalar in your schema, define the scalar like shown below for DateTime

scalar DateTime
  @specifiedBy(url: "https://scalars.graphql.org/andimarek/date-time.html")

type Something {
  someDateTime: DateTime
}

Custom Scalars

Alias Scalars

Scalar Definition Description
scalar AliasedScalar
You can create aliases for existing scalars to add more semantic meaning to them.

For example a link to a social media post could be representing by a String but the name SocialMediaLink is a more semantically meaningful name for that scalar type.

For example, you would build it like this:

AliasedScalar socialMediaLink = ExtendedScalars.newAliasedScalar("SocialMediaLink")
        .aliasedScalar(Scalars.GraphQLString)
        .build()

And use it in a SDL schema like this :

type Customer {
  name: String
  socialMediaLink: SocialMediaLink
}

Date & Time Scalars

Scalar Definition Description
scalar DateTime
  @specifiedBy(url: 
    "https://scalars.graphql.org/andimarek/date-time.html"
  )
A RFC-3339 compliant date time scalar that accepts string values like 1996-12-19T16:39:57-08:00 and produces java.time.OffsetDateTime objects at runtime.
scalar Date
  @specifiedBy(url: 
    "https://tools.ietf.org/html/rfc3339"
  )
A RFC-3339 compliant date scalar that accepts string values like 1996-12-19 and produces java.time.LocalDate objects at runtime.
scalar Time
  @specifiedBy(url: 
    "https://tools.ietf.org/html/rfc3339"
  )
A RFC-3339 compliant time scalar that accepts string values like 16:39:57-08:00 and produces java.time.OffsetTime objects at runtime.
scalar LocalTime
24-hour clock time string in the format hh:mm:ss.sss or hh:mm:ss if partial seconds is zero and produces java.time.LocalTime objects at runtime.

An example declaration in SDL might be:

type Customer {
  birthDay: Date
  workStartTime: Time
  bornAt: DateTime
}

type Query {
  customers(bornAfter: DateTime): [Customers]
}

And example query might look like:

query {
  customers(bornAfter: "1996-12-19T16:39:57-08:00") {
    birthDay
    bornAt
  }
}

ID Scalars

Scalar Definition Description
scalar UUID
  @specifiedBy(url: 
    "https://tools.ietf.org/html/rfc4122"
  )
A universally unique identifier scalar that accepts uuid values like 2423f0a0-3b81-4115-a189-18df8b35e8fc and produces java.util.UUID instances at runtime.

Numeric Scalars

Scalar Definition Description
scalar PositiveInt
An Int scalar that MUST be greater than zero.
scalar NegativeInt
An Int scalar that MUST be less than zero.
scalar NonPositiveInt
An Int scalar that MUST be less than or equal to zero.
scalar NonNegativeInt
An Int scalar that MUST be greater than or equal to zero.
scalar PositiveFloat
An Float scalar that MUST be greater than zero.
scalar NegativeFloat
An Float scalar that MUST be less than zero.
scalar NonPositiveFloat
An Float scalar that MUST be less than or equal to zero.
scalar NonNegativeFloat
An Float scalar that MUST be greater than or equal to zero.

The numeric scalars are derivations of the standard GraphQL Int and Float scalars that enforce range limits.

An example declaration in SDL might be:

type Customer {
  name: String
  currentHeight: PositiveInt
  weightLossGoal: NonPositiveInt
  averageWeightLoss: NegativeFloat
}

type Query {
  customers(height: PositiveInt): [Customers]
}

And example query might look like:

query {
  customers(height: 182) {
    name
    height
    weightLossGoal
  }
}

Java Primitives

Scalar Definition Description
scalar GraphQLLong
A scalar which represents java.lang.Long
scalar GraphQLShort
A scalar which represents java.lang.Short
scalar GraphQLByte
A scalar which represents java.lang.Byte
scalar GraphQLBigDecimal
A scalar which represents java.math.BigDecimal
scalar GraphQLBigInteger
A scalar which represents java.math.BigInteger
scalar GraphQLChar
A scalar which represents java.lang.Character

Locale Scalar

Scalar Definition Description
scalar Locale
  @specifiedBy(url: 
    "https://tools.ietf.org/html/bcp47"
  )
The Locale scalar handles IETF BCP 47 language tags via the JDK method Locale.forLanguageTag.
type Customer {
  name: String
  locale: Locale
}

type Query {
  customers(inLocale: Locale): [Customers]
}

An example query to look for customers in the Romanian locale might look like:

query {
  customers(inLocale: "ro-RO") {
    name
    locale
  }
}

Country Code Scalar

Scalar Definition Description
scalar CountryCode 
  @specifiedBy(url: 
    "https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2"
  )
The CountryCode scalar type as defined by ISO 3166-1 alpha-2.

An example declaration in SDL might be:

scalar CountryCode

type Customer {
  name: String
  countryCode: CountryCode
}

And example query might look like:

query {
  customers(code: "US") {
    name
    countryCode
  }
}

Currency Scalar

Scalar Definition Description
scalar Currency
  @specifiedBy(url: 
    "https://en.wikipedia.org/wiki/ISO_4217"
  )
A field whose value is an ISO-4217 currency.

An example declaration in SDL might be:

scalar Currency

type Account {
  id: String
  currency: Currency
  accountNumber: String
}

And example query might look like:

query {
  accounts(currency: "USD") {
    id
    currency
    accountNumber
  }
}

URL Scalars

Scalar Definition Description
scalar URL
  @specifiedBy(url: 
    "https://www.w3.org/Addressing/URL/url-spec.txt"
  )
An url scalar that accepts string values like https://www.w3.org/Addressing/URL/url-spec.txt and produces java.net.URL objects at runtime.

Object / JSON Scalars

Scalar Definition Description
scalar Object
An object scalar that accepts any object as a scalar value.
scalar JSON
A synonym for the Object scalar, it will accept any object as a scalar value.

One of the design goals of GraphQL, is that the type system describes the shape of the data returned.

The Object / JSON scalars work against this some what because they can return compound values outside the type system. As such they should be used sparingly. In general your should aim to describe the data via the GraphQL type system where you can and only resort to the Object / JSON scalars in very rare circumstances.

An example might be an extensible GraphQL system where systems can input custom metadata objects that cant be known at schema type design time.

An example declaration in SDL might be:

type Customer {
  name: String
  associatedMetaData: JSON
}

type Query {
  customers(filterSyntax: JSON): [Customers]
}

And example query might look like:

query {
  customers(
    filterSyntax: {
      startSpan: "First"
      matchCriteria: { countryCode: "AU", isoCodes: ["27B-34R", "95A-E23"] }
    }
  ) {
    name
    associatedMetaData
  }
}

Note : The JSON scalar is a simple alias type to the Object scalar because often the returned data is a blob of JSON. They are all just objects at runtime in graphql-java terms and what network serialization protocol is up to you. Choose whichever name you think adds more semantic readers to your schema consumers.

Regex Scalars

Scalar Name Description
RegexScalar Allows you to build a new scalar via a builder pattern using regular expressions.

The RegexScalar has a builder where you provide one or more regex patterns that control the acceptable values for a new scalar.

You name the scalar and it provides an implementation.

For example, imagine a phoneNumber scalar like this :

    RegexScalar phoneNumberScalar = ExtendedScalars.newRegexScalar("phoneNumber")
            .addPattern(Pattern.compile("\\([0-9]*\\)[0-9]*"))
            .build()