Relying on GraphQL enums validation in server-side Relying on GraphQL enums validation in server-side mongoose mongoose

Relying on GraphQL enums validation in server-side


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.


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.