如何处理 GraphQL Schema 定义中的连字符

tec*_*rek 2 mongoose mongodb mongoose-schema graphql graphql-js

我的猫鼬模式如下

var ImageFormats = new Schema({
     svg        : String,
     png-xlarge : String,
     png-small  : String
});
Run Code Online (Sandbox Code Playgroud)

当我将其翻译成 GraphQL 模式时,这就是我尝试的

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

     fields: {
          svg        : { type: GraphQLString },
         'png-xlarge': { type: GraphQLString },
         'png-small' : { type: GraphQLString }
 }
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ahm*_*ous 5

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

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

如果我尝试在 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;
    },
},
Run Code Online (Sandbox Code Playgroud)