|
| 1 | +package graphql.scalars.locale; |
| 2 | + |
| 3 | +import static graphql.scalars.util.Kit.typeName; |
| 4 | + |
| 5 | +import graphql.Internal; |
| 6 | +import graphql.language.StringValue; |
| 7 | +import graphql.schema.Coercing; |
| 8 | +import graphql.schema.CoercingParseLiteralException; |
| 9 | +import graphql.schema.CoercingParseValueException; |
| 10 | +import graphql.schema.CoercingSerializeException; |
| 11 | +import graphql.schema.GraphQLScalarType; |
| 12 | +import java.util.Locale; |
| 13 | + |
| 14 | +/** |
| 15 | + * Access this via {@link graphql.scalars.ExtendedScalars#Locale} |
| 16 | + */ |
| 17 | +@Internal |
| 18 | +public class LocaleScalar extends GraphQLScalarType { |
| 19 | + |
| 20 | + public LocaleScalar() { |
| 21 | + super("Locale", "A IETF BCP 47 language tag", new Coercing<Locale, String>() { |
| 22 | + |
| 23 | + @Override |
| 24 | + public String serialize(Object input) throws CoercingSerializeException { |
| 25 | + if (input instanceof String) { |
| 26 | + try { |
| 27 | + return Locale.forLanguageTag((String) input).toLanguageTag(); |
| 28 | + } catch (Exception e) { |
| 29 | + throw new CoercingSerializeException( |
| 30 | + "Expected a valid language tag string but was but was " + typeName(input)); |
| 31 | + } |
| 32 | + } |
| 33 | + if (input instanceof Locale) { |
| 34 | + return ((Locale) input).toLanguageTag(); |
| 35 | + } else { |
| 36 | + throw new CoercingSerializeException( |
| 37 | + "Expected a 'java.util.Locale' object but was " + typeName(input)); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public Locale parseValue(Object input) throws CoercingParseValueException { |
| 43 | + if (input instanceof String) { |
| 44 | + try { |
| 45 | + return Locale.forLanguageTag(input.toString()); |
| 46 | + } catch (Exception e) { |
| 47 | + throw new CoercingParseValueException( |
| 48 | + "Unable to parse value to 'java.util.Locale' because of: " + e.getMessage()); |
| 49 | + } |
| 50 | + } else { |
| 51 | + throw new CoercingParseValueException( |
| 52 | + "Expected a 'java.lang.String' object but was " + typeName(input)); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public Locale parseLiteral(Object input) throws CoercingParseLiteralException { |
| 58 | + if (input instanceof StringValue) { |
| 59 | + return Locale.forLanguageTag(((StringValue) input).getValue()); |
| 60 | + } else { |
| 61 | + throw new CoercingParseLiteralException( |
| 62 | + "Expected a 'java.lang.String' object but was " + typeName(input)); |
| 63 | + } |
| 64 | + } |
| 65 | + }); |
| 66 | + } |
| 67 | +} |
0 commit comments