francesco.venica
francesco.venica

Reputation: 1721

Dynamic GraphQLObjectType

I'm trying to create a dynamic GraphQLObjectType with graphQl, something like this:

export const Project = (data) => {
  return new GraphQLObjectType({
    name: 'Project',
    fields: () => ({
      id: {
        type: GraphQLString
      },
      type: {
        type: GraphQLString
      },
      author: {
        type: User,
        resolve: (root, args, req) => {
          ...
        }
      }
    })
  })
};

I call this model on my query in this way:

getProjectById: {
    type: Project(structure),
    args: {
      id: { type: GraphQLString }
    },
    resolve(source, args, req) {
      const projectService = new ProjectService(req);
      return projectService.getProjectById(args.id)
    }
  }

the problem is that doing this I get this error:

Schema must contain unique named types but contains multiple types named "Project"

where is the error? do you have some advice? many thanks

Upvotes: 0

Views: 132

Answers (1)

lipp
lipp

Reputation: 5956

The call Project(structure) in turn calls new GraphQLObjectType({name: 'Project',...}) . If you invoke Project(structure) more than once, you try to declare multiple GraphQLObjectTypes with the same name (which makes no sense).

If you would create/declare GraphQLObjectType dynamically, you have to generate a unique name property. E.g. like this:

// assuming data.name is unique export const Project = (data) => { return new GraphQLObjectType({ name: `Project${data.name}`, ... }) }

Upvotes: 1

Related Questions