繁体   English   中英

如何在GRAPHQL中设置默认值

[英]How to set a default value in GRAPHQL

我想在角色属性中设置一个默认值,但我不知道该怎么做。 这个想法是默认情况下所有用户的角色属性都是“BASIC”。 我用快递。

对不起我的英语,我不是本地人,这是代码:

 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}

}
),

});

谢谢你!

这已经在https://stackoverflow.com/a/51567429/10310278上得到解答

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

请检查这些东西。

这是通过defaultValue属性完成的。 但这对于您显示的GraphQLObjectType是不可能的。

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

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

所以GraphQLObjectType没有默认的 Value 属性。

你需要在不同的地方解决这个问题,而不是在这里。 比如在使用数据的时候,如果你想要的值是空的,那么可以使用default代替。

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

但是这个defaultValue属性在什么地方起作用呢? 它适用于GraphQLInputObjectType

例如:

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

我们可以这样使用它:

  ...
  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