【问题标题】:Is it possible to rename a field when creating a type within a GraphQL schema?在 GraphQL 模式中创建类型时是否可以重命名字段?
【发布时间】:2019-03-07 08:26:55
【问题描述】:

在服务器上的以下 GraphQL 模式中定义 userType 时,如何在仍然引用 fakeDatabase 中的“名称”字段的同时将“名称”字段重命名为“名字”?强>

以下代码sn-p是从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');

【问题讨论】:

    标签: graphql


    【解决方案1】:

    解析器可用于任何类型,而不仅仅是QueryMutation。这意味着您可以轻松地执行以下操作:

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

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

    【讨论】:

    • 哦。我是否正确地说,当没有为字段提供字段解析器时, 的解析器默认为 resolve: (parent, args, ctx) => parent.<fieldName>
    • 基本上,是的。 “默认解析器”将在父对象中查找与字段名称匹配的属性。如果属性是一个函数,它将调用该函数并返回结果。如果属性不是函数,它将返回值,假设它可以被强制转换为为该特定字段指定的任何类型。
    • 如果您想看一看,Apollo 文档会很好地详细解释它:apollographql.com/docs/graphql-tools/…
    【解决方案2】:

    还有一个库 graphql-tools 可以让您转换您的架构,我们在我们的架构拼接服务中使用它。

    const { RenameTypes, transformSchema } = require("graphql-tools");
    
    /*
     * Schema transformations:
     * Types:
     *  <> Task -> GetTask
     */
    
    const transformMySchema = schema => {
      return transformSchema(schema, [
        new RenameTypes(function(name) {
          return name == "Task" ? "GetTask" : name;
        }),
      ]);
    };
    

    阅读更多:https://github.com/apollographql/graphql-tools/blob/513108b1a6928730e347191527cba07d68aadb74/docs/source/schema-transforms.md#modifying-types

    这能回答问题吗?

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2019-11-22
      • 2011-03-06
      • 2021-08-04
      相关资源
      最近更新 更多