How to handle hyphens in GraphQL Schema definition

2019-08-04 16:14发布

My mongoose schema is as follows

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

When I translate this into a GraphQL Schema, this is what I try

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

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

GraphQL Returns the following error: Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "png-xlarge" does not.

If I am trying to model the GraphQL after my Mongoose model, how can I reconcile the fields? Is there a way for me to create an alias?

(I have searched for this on the graffiti and stackoverflow forums but could not find a similar question)

1条回答
Explosion°爆炸
2楼-- · 2019-08-04 16:35

GraphQL Returns the following error: Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "png-xlarge" does not.

GraphQL complains that field name 'png-xlarge' is invalid. The regular expression in error message says that the first character can be a letter irrespective of case or underscore. The remaining characters can also have digit. Therefore, it is clear that neither hyphen - nor single quote ' is acceptable for a field name. The rules basically follow the variable naming rules that you find in almost every programming language. You can check the GraphQL naming rules.

If I am trying to model the GraphQL after my Mongoose model, how can I reconcile the fields? Is there a way for me to create an alias?

With the help of resolve function, you can do this as follows:

pngXLarge: { 
    type: GraphQLString,
    resolve: (imageFormats) => {
        // get the value `xlarge` from the passed mongoose object 'imageFormats'
        const xlarge = imageFormats['png-xlarge'];
        return xlarge;
    },
},
查看更多
登录 后发表回答