【问题标题】:apollo-server-express: how to resolve inside subscriptions?apollo-server-express:如何解决内部订阅问题?
【发布时间】:2018-06-17 22:24:12
【问题描述】:

在执行常规 graphQL 查询时,我可以轻松获取嵌套对象或计算。 但是当在订阅中时,例如:

subscription {
  Event(filter: {
    mutation_in: [CREATED]
  }) {
    node {
      title
      description
      start
      end
      seats
      bookings
      owner {
        email
      }
    }
  }
}

我一添加bookings 或owner { ... },它就会中断。我在当时的服务器上没有看到错误消息。 QraphiQL 仅显示 [object Object] 作为响应。

有趣的模式是:

type Event {
  id: ID!
  title: String!
  description: String!
  owner: User!
  seats: Int
  bookings: Int
  start: DateTime!
  end: DateTime!
  tickets: [EventTicket!]!
}


type Mutation {
  createEvent(event: EventInput!): Event
}
input EventInput {
  title: String!
  description: String!
  seats: Int
  start: DateTime!
  end: DateTime!
}


type Subscription {
  Event(filter: EventSubscriptionFilter): EventSubscriptionPayload
}
input EventSubscriptionFilter {
  mutation_in: [_ModelMutationType!]
}
type EventSubscriptionPayload {
  mutation: _ModelMutationType!
  node: Event
}
enum _ModelMutationType {
  CREATED
  UPDATED
  DELETED
}

以及解析器:

import { ObjectId } from "mongodb"
import pubsub from "../../utils/pubsub"

export default {
  // ...
  Mutation: {
    createEvent: async (_, data, { mongo: { Events }, user }) => {
      const newEvent = data.event
      newEvent.ownerId = user._id
      const response = await Events.insert(newEvent)
      const [_id] = response.insertedIds
      newEvent._id = _id
      pubsub.publish("Event", { Event: { mutation: "CREATED", node: newEvent } })
      return newEvent
    },
  },
  Subscription: {
    Event: {
      subscribe: () => pubsub.asyncIterator("Event"),
    },
  },
  Event: {
    id: event => event._id.toString(),
    owner: async (event, _, { mongo: { Users } }) => Users.findOne({ _id: event.ownerId }),
    bookings: async (event, _, { mongo: { EventTickets } }) =>
      EventTickets.find({ eventId: event._id }).count(),
    tickets: async (event, _, { mongo: { EventTickets } }) =>
      EventTickets.find({ eventId: event._id }).toArray(),
  },
}

关于如何处理这个问题的任何想法(和/或如何获得正确的错误消息以进行调试^^)。

【问题讨论】:

    标签: graphql apollo apollo-server


    【解决方案1】:

    搜索后确定,I found the solution/hack here。

        SubscriptionServer.create(
            {
               execute, subscribe, schema,
               onOperation: (message, params, webSocket) => {
                return { ...params, context: {mongo} }
              },
            },
            { server, path: '/subscriptions' },
        );
    

    谢谢nharraud。

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 2020-08-11
      • 2019-06-26
      • 2021-02-05
      • 2018-06-09
      • 2020-04-23
      • 2022-12-12
      • 2021-01-18
      • 2020-08-08
      相关资源
      最近更新 更多