1

我有以下可以正常工作的订阅查询:

subscription{
  streamShipmentOrder{
    id
  }
}

但以下发送“无法读取未定义的属性'ShipmentOrder'”错误

subscription{
  streamShipmentOrder{
    id
    logs{
      comment
    }
  }
}

这是我的 ShipmentOrder 类型定义,我正在使用sequelize与数据库通信

const ShipmentOrderType = new GraphQLObjectType({
    name: 'ShipmentOrder',
    fields: () => ({
       id: { type: GraphQLID },
       logs: {
          type: new GraphQLList(LogType),
          resolve: async (parent, args, { models }, info) => {
             return await models.ShipmentOrder.findOne({
                where: { id: parent.id },
                include: [{ model: models.Log }],
             }).then((data) => data.logs);
          }
       },
    }

这是订阅定义

const ShipmentOrderSubscription = new GraphQLObjectType({
   name: 'Subscription',
   fields: () => ({
      streamShipmentOrder: {
         type: ShipmentOrderType,
         resolve: (payload) => payload.shipmentOrderData,
         subscribe: () =>
            socket.asyncIterator([
               SHIPMENT_ORDER_CREATED,
               SHIPMENT_ORDER_UPDATED,
               SHIPMENT_ORDER_DELETED
            ]),
      },
   }),
});

以及触发订阅的突变,(在请求嵌套结果时,突变也可以正常工作)

const ShipmentOrderMutation = new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
        createShipmentOrder: {
            type: ShipmentOrderType,
            args: {...},
            resolve: async (parent, args, { models }, info) => {

                // create shipmentOrder
                return await models.ShipmentOrder.create({...})
                    .then(async (createdShipmentOrder) => {

                    // create log and relate to created shipmentOrder
                    await models.Log.create({...});

                    // get created shipmentOrder with its logs
                    return await models.ShipmentOrder.findOne({
                        where: { id: createdShipmentOrder.id },
                        include: [{ model: models.Log }],
                    }).then((foundShipmentOrder) => {

                        // updates streams
                        socket.publish(SHIPMENT_ORDER_CREATED, {
                            shipmentOrderData: foundShipmentOrder,
                        });
                        return foundShipmentOrder;

                    });
                }
            }
        }
    })
});

我会错过什么?

4

1 回答 1

0

正如@DanielRearden 指出的那样,调用订阅时context 是空的,这搞乱了我的关系,这是因为 context 在 query/mutations 和 subscriptions 上的处理方式不同

所以修复它的方法是将我的模型对象添加到ApolloServer 中订阅选项的onConnect属性,将我已经传递给我的上下文选项的相同对象传递给

const server = new ApolloServer({
    schema,
    subscriptions: {
        onConnect: () => ({models}),
    },
    context: () => ({models})
}
于 2018-11-25T23:57:33.307 回答