【问题标题】:How to handle hyphens in GraphQL Schema definitions如何处理 GraphQL Schema 定义中的连字符
【发布时间】:2017-05-16 14:09:00
【问题描述】:

我的猫鼬架构如下

var ImageFormats = new Schema({
     svg        : String,
     png-xlarge : String,
     png-small  : String
});

当我将其转换为 GraphQL Schema 时,我尝试这样做

export var GQImageFormatsType: ObjectType = new ObjectType({
     name: 'ImageFormats',

     fields: {
          svg        : { type: GraphQLString },
         'png-xlarge': { type: GraphQLString },
         'png-small' : { type: GraphQLString }
 }
});

GraphQL 返回以下错误:Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "png-xlarge" does not.

如果我尝试在 Mongoose 模型之后对 GraphQL 进行建模,我该如何协调这些字段?我有办法创建别名吗?

(我在 graffiti 和 stackoverflow 论坛上搜索过这个,但找不到类似的问题)

【问题讨论】:

  • 在您上面的代码(猫鼬模式)中,您没有声明 png-lg 属性
  • @Medet_Tleukabiluly 抱歉,我粘贴了错误的错误消息。它确实引用了猫鼬模式的 png-xlarge 属性。有什么想法吗?
  • 尝试显式定义 mongoose 架构的默认值 png-xlarge : { type: String, default: '' },可能 mongoose 空值与 GraphQLString 空值不同
  • @MedetTleukabiluly 这不起作用。问题肯定和字段名有关,graphQLs 代码库也证实了这一点。

标签: mongodb mongoose graphql mongoose-schema graphql-js


【解决方案1】:

GraphQL 返回以下错误:错误:名称必须匹配 /^[_a-zA-Z][_a-zA-Z0-9]*$/ 但“png-xlarge”不匹配。

GraphQL 抱怨字段名称 'png-xlarge' 无效。错误消息中的正则表达式表示第一个字符可以是字母,不考虑大小写或下划线。其余字符也可以有数字。因此,很明显,连字符- 和单引号' 都不能用于字段名称。这些规则基本上遵循几乎所有编程语言中的变量命名规则。您可以查看GraphQL naming rules

如果我尝试在 Mongoose 模型之后对 GraphQL 进行建模,我该如何协调这些字段?我有办法创建别名吗?

resolve函数的帮助下,你可以这样做:

pngXLarge: { 
    type: GraphQLString,
    resolve: (imageFormats) => {
        // get the value `xlarge` from the passed mongoose object 'imageFormats'
        const xlarge = imageFormats['png-xlarge'];
        return xlarge;
    },
},

【讨论】:

  • 感谢这是完美的@ahmad-ferdous
猜你喜欢
  • 2023-01-05
  • 2016-03-17
  • 2020-04-06
  • 2019-12-07
  • 1970-01-01
  • 2020-06-20
  • 2019-11-15
  • 2020-07-27
相关资源
最近更新 更多