【问题标题】:graphql required fields approachgraphql必填字段方法
【发布时间】:2017-10-27 16:44:23
【问题描述】:

这是我的 graphql 架构、查询和突变。

我在架构中用“!”标记了必填字段

如何创建突变以添加新客户端?

我真的需要再次编写相同的必填字段吗?

点赞createClient(contactMethod: String!, hearAbout: String! ......... ): Client


const typeShard = `
  type ClientProfile {
    name: String!
    surname: String!
    address: String
    language: String!
  }

  type Client {
    _id: String
    isEdit: Boolean
    createdAt: String
    shortId: Int
    profile: ClientProfile
    comments: String
    contactMethod: String!
    hearAbout: String!
    leadAgentId: String
    branchId: String!
  }
`;

const queryShard = `
  getAllClients: [Client]
`;

const mutationShard = `
  removeClient(shortId : Int!): Client
  createClient(contactMethod: String!, hearAbout: String!   .........  ): Client
`;

const resolvers = {
  Query: {
    getAllClients: () => MongoClients.find().fetch(),
  },
  Mutation: {
    removeClient(root, { shortId }) {
      const client = MongoClients.findOne({ shortId });
      if (!client) throw new Error(`Couldn't find client with id ${shortId}`);
      MongoClients.remove({ shortId });
      return client;
    },
    createClient: (_, args) => {
      return MongoClients.insert(args);
    },
  },
};

【问题讨论】:

    标签: graphql apollo apollo-server


    【解决方案1】:

    您不需要为每个突变编写相同的字段。你可以定义一个input 类型。请看看这个cheat sheet

    所以在你的情况下,它可能看起来像:

    const typeShard = `
      type ClientProfile {
        name: String!
        surname: String!
        address: String
        language: String!
      }
    
      type Client {
        _id: String
        isEdit: Boolean
        createdAt: String
        shortId: Int
        profile: ClientProfile
        comments: String
        contactMethod: String!
        hearAbout: String!
        leadAgentId: String
        branchId: String!
      }
      input ClientInput {
        contactMethod: String!
        hearAbout: String!
        .....
      }
    `;
    
    const mutationShard = `
      removeClient(shortId : Int!): Client
      createClient(clientInput: ClientInput!): Client
    `;

    【讨论】:

    • 感谢您的回答。我读过它。但是可以结合输入和输出吗?在许多情况下,这将是代码重复。有什么想法吗?
    • 我认为不可能
    猜你喜欢
    • 2019-03-01
    • 2017-06-09
    • 2014-01-02
    • 2014-10-29
    • 2020-04-06
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多