0

I wanna set a default value in the role property but I don´t know how to do it. The idea is that the role property is "BASIC" by default for all users. I´m using express.

Sorry for my english, I´m not native, this is the code:

 const UserType = new GraphQLObjectType({

name: "User",
description: "User type",
fields: () => ({
id: { type: GraphQLID },
username: { type: GraphQLString },
email: { type: GraphQLString },
displayName: { type: GraphQLString },
phone: { type: GraphQLString },
role: { type:  GraphQLString}

}
),

});

thank you!

Pr0g4mmer
  • 33
  • 1
  • 3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 25 '22 at 13:10

2 Answers2

0

This is already answered on https://stackoverflow.com/a/51567429/10310278

And official documentation https://graphql.org/graphql-js/type/#example-5

Please check these things out.

cvekaso
  • 833
  • 1
  • 11
  • 28
  • I tried to do that but it doesn´t work with my code but It probably is because I don't know how to apply it to my code – Pr0g4mmer Mar 25 '22 at 12:37
0

This is done with the defaultValue property. But this is not possible for the GraphQLObjectType as you show.

const UserType = new GraphQLObjectType({
  name: 'User',
  description: 'User type',
  fields: () => ({
    id: { type: GraphQLID },
    username: { type: GraphQLString, defaultValue: 'default string' },
  }),
});

Object literal may only specify known properties, and 'defaultValue' does not exist in type 'GraphQLFieldConfig<any, any, { [argName: string]: any; }>'

So GraphQLObjectType has no default Value property.

You need to solve this in a different place, not here. For example, when using data, if the value you want is empty, you can use default instead.

...
...
data.username ?? 'default string'
...
...

But where does this defaultValue property work? It works with GraphQLInputObjectType.

For example:

  const filter = new GraphQLInputObjectType({
    name: "Filter",
    fields: () => ({
      min: { type: new GraphQLNonNull(graphql.GraphQLInt) },
      max: { type: graphql.GraphQLBoolean, defaultValue: 100 },
    }),
  });

and we can use it like this:

  ...
  query: {
    products: {
      type: new GraphQLList(productTypes),
      args: { filter: { type: new GraphQLNonNull(filter) } }, // <-----
      resolve: allProducts,
    },
  },
  ...
sha'an
  • 1,032
  • 1
  • 11
  • 24