graphql - 在 GraphQL 模式中创建类型时是否可以重命名字段?
问题描述
在服务器上定义userType
以下 GraphQL 模式时,如何将“name”字段重命名为“firstname”,同时仍引用中的“name”字段fakeDatabase
?
以下代码片段已从官方 GraphQL 文档中复制
var express = require('express');
var graphqlHTTP = require('express-graphql');
var graphql = require('graphql');
// Maps id to User object
var fakeDatabase = {
'a': {
id: 'a',
name: 'alice',
},
'b': {
id: 'b',
name: 'bob',
},
};
// Define the User type
var userType = new graphql.GraphQLObjectType({
name: 'User',
fields: {
id: { type: graphql.GraphQLString },
// How can I change the name of this field to "firstname" while still referencing "name" in our database?
name: { type: graphql.GraphQLString },
}
});
// Define the Query type
var queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: userType,
// `args` describes the arguments that the `user` query accepts
args: {
id: { type: graphql.GraphQLString }
},
resolve: function (_, {id}) {
return fakeDatabase[id];
}
}
}
});
var schema = new graphql.GraphQLSchema({query: queryType});
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
解决方案
解析器可用于任何类型,而不仅仅是Query
and Mutation
。这意味着您可以轻松地执行以下操作:
const userType = new graphql.GraphQLObjectType({
name: 'User',
fields: {
id: {
type: graphql.GraphQLString,
},
firstName: {
type: graphql.GraphQLString,
resolve: (user, args, ctx) => user.name
},
}
})
解析器函数在给定父值、该字段的参数和上下文的情况下指定类型的任何实例的字段将解析为什么。它甚至可以每次都返回相同的静态值。
推荐阅读
- java - 在 com.example.accountproject.models.interfaces.MemberSv 定义中创建名称为“memberSv”的 bean 时出错
- dependency-injection - 如何使用匕首提供列表适配器类的依赖关系?- 当适配器类将接口作为参数时
- react-native - 如何在 .map 循环笑话测试库中覆盖 onPress 的 touchableOpacity
- javascript - 如何使用 javascript 从内部更改父 iframe 大小?
- javascript - 如何在 javascript 中访问多个嵌套的子对象?
- laravel - 引导模式上的 laravel 文件管理器
- react-native - 如何在 React Native 中创建调试 apk 文件
- reactjs - 在 ReactJS 中的图表内添加数据标签不起作用?
- android - glide 加载资源失败,刷新后成功
- java - ActiveMQ artemis - 如何制作监听进程