| 30 | import org.jspecify.annotations.Nullable; |
| 31 | |
| 32 | class Types { |
| 33 | |
| 34 | static final GraphQLScalarType Url = urlType(); |
| 35 | static final GraphQLScalarType Uri = uriType(); |
| 36 | |
| 37 | private static GraphQLScalarType uriType() { |
| 38 | return GraphQLScalarType.newScalar() |
| 39 | .name("Uri") |
| 40 | .coercing( |
| 41 | new Coercing<URI, String>() { |
| 42 | @Override |
| 43 | public String serialize(Object o) throws CoercingSerializeException { |
| 44 | if (o instanceof String) { |
| 45 | return (String) o; |
| 46 | } |
| 47 | |
| 48 | if (o instanceof URL || o instanceof URI) { |
| 49 | return String.valueOf(o); |
| 50 | } |
| 51 | |
| 52 | throw new CoercingSerializeException("Unable to coerce " + o); |
| 53 | } |
| 54 | |
| 55 | @Override |
| 56 | public URI parseValue(Object input) throws CoercingParseValueException { |
| 57 | if (input instanceof URI) { |
| 58 | return (URI) input; |
| 59 | } |
| 60 | |
| 61 | try { |
| 62 | if (input instanceof String) { |
| 63 | return new URI((String) input); |
| 64 | } |
| 65 | |
| 66 | if (input instanceof URL) { |
| 67 | return ((URL) input).toURI(); |
| 68 | } |
| 69 | } catch (URISyntaxException e) { |
| 70 | throw new CoercingParseValueException("Unable to create URI: " + input, e); |
| 71 | } |
| 72 | |
| 73 | throw new CoercingParseValueException("Unable to create URI: " + input); |
| 74 | } |
| 75 | |
| 76 | @Override |
| 77 | public URI parseLiteral(Object input) throws CoercingParseLiteralException { |
| 78 | if (!(input instanceof StringValue)) { |
| 79 | throw new CoercingParseLiteralException("Cannot convert to URL: " + input); |
| 80 | } |
| 81 | |
| 82 | try { |
| 83 | return new URI(((StringValue) input).getValue()); |
| 84 | } catch (URISyntaxException e) { |
| 85 | throw new CoercingParseLiteralException("Unable to parse: " + input); |
| 86 | } |
| 87 | } |
| 88 | }) |
| 89 | .build(); |