【问题标题】:how to reuse resolvers in graphql如何在graphql中重用解析器
【发布时间】:2017-10-03 23:10:33
【问题描述】:

我是 graphql 的新手,我正在使用 graphql 创建以下架构

// promotion type

const PromoType = new GraphQLObjectType({
  name: 'Promo',
  description: 'Promo object',
  fields: () => ({
    id: {
      type: GraphQLID,
      description: 'id of the promo'
    },
    title: {
      type: GraphQLString,
      description: 'this is just a test'
    },
    departments: {
      type: new GraphQLList(DepartmentType),
      description: 'departments associated with the promo'
    }
  })
})

部门类型

// department type

const DepartmentType = new GraphQLObjectType({
  name: 'Department',
  description: 'Department object',
  fields: () => ({
    id: {
      type: GraphQLID,
      description: 'id of the department'
    },
    name: {
      type: GraphQLString,
      description: 'name of the department'
    },
    createdAt: {
      type: GraphQLDate,
      description: 'date the promo is created'
    },
    updatedAt: {
      type: GraphQLDate,
      description: 'date the promo is last updated'
    }
  })
});

以下是解析器

// Promos resolver

const promos = {
  type: new GraphQLList(PromoType),
  resolve: (_, args, context) => {

    let promos = getPromos()
    let departments = getDepartmentsById(promos.promoId)
    return merge(promos, departments)
  }
};


//Departments resolver
const departments = {
  type: new GraphQLList(DepartmentType),
  args: {
      promoId: {
      type: GraphQLID
    }
  },
  resolve: (_, args, context) => {

    return getDepartmentsById(args.promoId)
  }
};

问题是我想使用部门的解析器进入促销的解析器来获取部门。

我可能遗漏了一些明显的东西,但有什么办法可以做到这一点?

【问题讨论】:

    标签: graphql graphql-js apollo


    【解决方案1】:

    这是实现它的方法。您想将其视为图形,而不仅仅是单个休息端点。

    要获取Promo 的数据,您需要与我在此处的操作类似,但对于父节点,如果这有意义的话。所以,在例如查看者决定您添加查询Promo

    const PromoType = new GraphQLObjectType({
      name: 'Promo',
      description: 'Promo object',
      fields: () => ({
        id: {
          type: GraphQLID,
          description: 'id of the promo',
        },
        title: {
          type: GraphQLString,
          description: 'this is just a test',
        },
        departments: {
          type: new GraphQLList(DepartmentType),
          description: 'departments associated with the promo',
          resolve: (rootValue) => {
            return getDepartmentsById(rootValue.promoId);
          }
        }
      })
    });
    

    【讨论】:

    • 我的意思是我不想为单个字段编写解析器,如果有任何“自动”方法可以做到这一点。我已经使用了 Apollo 工具和服务器。
    猜你喜欢
    • 2021-09-10
    • 2018-09-30
    • 1970-01-01
    • 2018-03-01
    • 2023-04-08
    • 2019-07-15
    • 1970-01-01
    • 2020-05-22
    • 2021-07-29
    相关资源
    最近更新 更多