sarkistlt / mongoose-schema-to-graphql

Use Mongoose schema to generate graphQL type.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Recursive Mongoose schema

comonadd opened this issue · comments

Suppose you are writing a forum API, which has a recursive schema called Message defined like this:

const MessageTypeMongoose = new mongoose.Schema({
  text: String,
});

// This is how you define recursive Mongoose schema
MessageTypeMongoose.add({
  messages: [MessageTypeMongoose],
});

Now, because you don't want to write the same thing two times, you are using mongoose-schema-to-graphql library, and the definition of your GraphQL schema looks like this:

const MessageTypeGraphQL = mongooseSchemaToGraphQL({
  name: 'Message',
  class: 'GraphQLObjectType',
  schema: MessageTypeMongoose,
});

But, when you would run this code, you will get a funny stack overflow error message, which looks like this:

RangeError: Maximum call size exceeded
  at Array.forEach (native)
  at createType( /*...*/ /node_modules/mongoose-schema-to-graph/lib/index.js:1:1747)
  //...

I've tried to figure out where is the infinite recursion happens:

  • First, if you pass a schema in which the recursively defined field is an array, the infinite recursion happens here

GQLS.fields[key] = { type: createType(subArgs) };

  • Second, if you pass a schema in which the recursively defined field is not an array, the infinite recursion happens here

const typeElement = createType(subArgs);

If we won't fix this issue, other users would be in a trouble, - they would waste big amount of time. It is very hard to figure out which mongooseSchemaToGraphQL call caused this problem.

NOTE: It is totally possible to define a recursive GraphQL type. Look at this SO answer.

Thanks for detailed information. Can you try new version? should be fixed.