简体   繁体   English

如何在GRAPHQL中设置默认值

[英]How to set a default value in GRAPHQL

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.这个想法是默认情况下所有用户的角色属性都是“BASIC”。 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!谢谢你!

This is already answered on https://stackoverflow.com/a/51567429/10310278这已经在https://stackoverflow.com/a/51567429/10310278上得到解答

And official documentation https://graphql.org/graphql-js/type/#example-5和官方文档https://graphql.org/graphql-js/type/#example-5

Please check these things out.请检查这些东西。

This is done with the defaultValue property.这是通过defaultValue属性完成的。 But this is not possible for the GraphQLObjectType as you show.但这对于您显示的GraphQLObjectType是不可能的。

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; Object literal 只能指定已知属性,并且类型 'GraphQLFieldConfig<any, any, { [argName: string]: any; 中不存在 'defaultValue'; }>' }>'

So GraphQLObjectType has no default Value property.所以GraphQLObjectType没有默认的 Value 属性。

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.比如在使用数据的时候,如果你想要的值是空的,那么可以使用default代替。

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

But where does this defaultValue property work?但是这个defaultValue属性在什么地方起作用呢? It works with GraphQLInputObjectType .它适用于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,
    },
  },
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM