Search code examples
mongodbmongoosegraphqlgraphql-js

Relying on GraphQL enums validation in server-side


My question is sort of what is the best practice to do?

I'm creating a backend that uses GraphQL as the API with MongoDB as the datastore. I know that graphql validates the query, in particular the received enums. My question is if it's enough to rely on the GraphQL input enum validation or should I also add validation at the DB level.

I ask this because it seems like a bad practice, and unneeded code duplication. You'll have in two places definitions of the possible enum types, one in the GraphQL schema and one the MongoDB model.

For example:

gql schema:
enum EyeColor {
BROWN
BLUE
GREEN
}

model in mongoose:
new mongoose.Schema({
eyeColor: { type: String, enum: ["BROWN", "BLUE", "GREEN"] }
});

Am i missing something? Is there a better way to declare enums with/in GraphQL or MongoDB? Or maybe it's okay to only rely on GraphQL?


Solution

  • I think that a better way is to define the enum in a const file EyeColor.const.js:

    const EYE_COLOR = {
      BROWN: 'BROWN',
      BLUE: 'BLUE',
      GREEN: 'GREEN'
    };
    
    export {
      EYE_COLOR
    };
    

    And then in your mongoose model file:

    import { EYE_COLOR } from '../../consts/EyeColor.const';
    import _ from 'lodash';
    new mongoose.Schema({ 
     eyeColor: {
        type: String,
        enum: _.values(EYE_COLOR)
      }
    }); 
    

    And for the graphql you can dynamically create the String which contains the enum

    enum EyeColor {
     BROWN 
     BLUE 
     GREEN 
    }
    

    From your object at EyeColor.const.js (I didn't write the code but it should be pretty simple - for each key in your const create another entry in the enum).

    This way you have only one definition of your consts.