GraphQL数组报错:构建Schema的类型缺失名称,[GraphQLID]写法是否正确
错误原因与修复方案
你定义GraphQLID数组的写法存在错误,这就是触发「One of the provided types for building the Schema is missing a name」报错的直接原因。
- 错误逻辑说明:在GraphQL.js原生语法规范中,不能直接使用JavaScript数组字面量
[GraphQLID]声明数组类型,必须调用官方提供的GraphQLList包装类定义数组类型。你直接为type字段赋值普通JS数组后,GraphQL构建Schema时无法识别该类型的名称,因此会抛出类型缺失名称的报错。 - 具体修复操作:
- 先从graphql依赖包中导入
GraphQLList类型:
// CommonJS导入写法 const { GraphQLString, GraphQLID, GraphQLList } = require('graphql'); // ES模块导入写法 // import { GraphQLString, GraphQLID, GraphQLList } from 'graphql';
- 修改
composers字段的类型声明:
const tvshowArgs = { name: { type: GraphQLString }, // 替换原有错误写法 type: [ GraphQLID ] composers: { type: new GraphQLList(GraphQLID) }, }
如果后续需要定义非空约束的数组类型,可以搭配GraphQLNonNull使用,示例:要求数组本身不可为空且内部每个ID都不为空的写法为new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID)))。
内容的提问来源于stack exchange,提问作者unicorn_surprise
相关产品推荐
相关产品推荐

