How can I use isValidJSValue to validate a query variable in my client code?

試著忘記壹切 提交于 2019-12-11 14:47:08

问题


I'm writing client-side code for an app that will query a GraphQL server. In a couple of places in my code, I'm passing around data that will eventually get turned into a query variable, so it needs to validate against a specific GraphQLInputType in my schema. On looking into some of the utilities that graphql-js provides, it looks like the isValidJSValue checker is exactly what I'm looking for, and its comments even mention that it's intended to be used to do just that.

The issue is that I don't have access to the GraphQL type I want to validate against as a JS object, which is what I'm pretty sure that function is looking for. I'm importing my schema (as an npm depdendency) as JSON, or I also have it in the schema notation. Is there some other utility I can use to get the JS type I need from one of those sources, and then use that to check my data with isValidJSValue? Or is there some other way I could go about this that I just haven't thought of?


回答1:


You can use the JSON schema you have imported to construct an actual GraphQL schema instance using buildClientSchema here: https://github.com/graphql/graphql-js/blob/master/src/utilities/buildClientSchema.js

Then, it should be a simple matter of looking in the types field of the resulting schema to find your input type, and then calling isValidJSValue on it.

I'm curious, though - why validate the value on the client before sending it, rather than just relying on the validation the server will do?



来源:https://stackoverflow.com/questions/38340892/how-can-i-use-isvalidjsvalue-to-validate-a-query-variable-in-my-client-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!