如何使用isValidJSValue验证客户端代码中的查询变量? [英] How can I use isValidJSValue to validate a query variable in my client code?

查看:88
本文介绍了如何使用isValidJSValue验证客户端代码中的查询变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为将查询GraphQL服务器的应用程序编写客户端代码.在我的代码中的几个地方,我传递了最终会变成查询变量的数据,因此它需要针对我架构中的特定GraphQLInputType进行验证.在研究graphql-js提供的某些实用程序时,看起来isValidJSValue检查器正是我正在寻找的东西,

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.

问题是我无法访问要作为JS对象进行验证的GraphQL类型,这是我确定该函数正在寻找的东西.我正在将我的架构(作为npm依赖关系)作为JSON导入,或者我也将其包含在架构符号中.是否可以使用其他实用程序从这些来源之一获取所需的JS类型,然后使用该实用程序通过isValidJSValue检查我的数据?还是我可以想到的其他方法呢?

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?

推荐答案

您可以在以下位置使用buildClientSchema使用导入的JSON模式来构建实际的GraphQL模式实例: com/graphql/graphql-js/blob/master/src/utilities/buildClientSchema.js"rel =" nofollow> https://github.com/graphql/graphql-js/blob/master/src/utilities/buildClientSchema. js

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

然后,只需查看结果模式的types字段以找到您的输入类型,然后在其上调用isValidJSValue即可.

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?

这篇关于如何使用isValidJSValue验证客户端代码中的查询变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆