How to handle hyphens in GraphQL Schema definitions

6.1k Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

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;
    },
},