在GraphQL模式中创建类型时可以重命名字段吗? [英] Is it possible to rename a field when creating a type within a GraphQL schema?

查看:73
本文介绍了在GraphQL模式中创建类型时可以重命名字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器上的以下GraphQL架构中定义 userType 时,如何在仍引用 fakeDatabase ?

When defining the userType in the following GraphQL schema on the server, how can I rename the "name" field to "firstname" while still referring to the "name" field in fakeDatabase?

以下代码段已从官方GraphQL文档中复制而来

The following code snippet has been copied from the official GraphQL docs

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 Mutation .这意味着您可以轻松地执行以下操作:

Resolvers can be used for any type, not just Query and Mutation. That means you can easily do something like this:

const userType = new graphql.GraphQLObjectType({
  name: 'User',
  fields: {
    id: {
      type: graphql.GraphQLString,
    },
    firstName: {
      type: graphql.GraphQLString,
      resolve: (user, args, ctx) => user.name
    },
  }
})

在给定父值的情况下,resolver函数指定该字段和上下文的参数,该类型的任何实例的字段将解析为什么.甚至每次都可以始终返回相同的静态值.

The resolver function specifies, given the parent value, arguments for that field and the context, what a field for any instance of a type will resolve to. It could even always return the same static value each time.

这篇关于在GraphQL模式中创建类型时可以重命名字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆