Daniel Jakobsen Hallel
Daniel Jakobsen Hallel

Reputation: 584

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?

Upvotes: 2

Views: 1479

Answers (2)

batjko
batjko

Reputation: 1062

In terms of "best practice", it does depend on how your database is used in the future: Is it coupled directly with your GraphQL server (and will only ever be accessed via that GraphQL API)? Then there is perhaps no need to duplicate that enum check.

However, if it's at all possible or even likely that Mongo could be accessed without going through GraphQL (e.g. by future modules or services accessing your mongoose functions), then you'll want to secure the data model on the mongoose level as well.

Upvotes: 3

yishaiz
yishaiz

Reputation: 2603

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.

Upvotes: 2

Related Questions