I just made a simple Scalar type/package for Node, graphql-scalar-json5.
It seems to me to be working as expected
But I got a question about it
seems like using this bypasses type-checking as opposed to using an input type?
It got me thinking I might be doing something wrong.
While you get an error, at resolve time, if the value is Not valid.
There is no warning in GraphiQL
I'm not sure if this is limitation of custom scalar types in GraphQL. or a GraphiQL implementation detail
At 1st impression it makes sense, that if a JSON5 (or JSON) value is effectively deriving from the String type, but I never told 'GraphQL' about it, and doesn't seem to be way to do so ...
How will the tool know the parameter is of the wrong type?
Taking another custom scalar, EmailAddress, from graphql-scalars
With the following Query definition
echoMail(email: EmailAddress): EmailAddress
Again, The type check only happens at runtime/resolver-time, as it needs to be parsed, by the resolver, to be validated.
Is there a better way to do this ?
As an example, given the following implementation
class MyScalar {
constructor(value) {
this.value = value;
}
toString() {
return this.value;
}
static from(value) {
if (typeof value !== "string")
throw new Error(`Expected 'String' but got '${typeof value}'`);
return new MyScalar(value);
}
}
new GraphQLScalarType({
name: "MyScalar",
serialize: (x) => x.toString(),
parseValue: MyScalar.from,
parseLiteral: (ast, variables) =>
Kind.VARIABLE
? (variables && MyScalar.from(variables[ast.name.value])) || undefined
: MyScalar.from(ast.value),
});
How would you improve it?
Does it make any difference where to validate the value ?
On serialize, on parseValue, on parseLiteral ?
Is there anything else to 'implement' ?
Thanks
