嵌套查询/解析器时,GraphQL.js订阅响应错误

时间:2018-11-25 06:04:37

标签: graphql-js apollo-server graphql-subscriptions

我有以下订阅查询,工作正常

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;

                    });
                }
            }
        }
    })
});

我可能会缺少什么?

1 个答案:

答案 0 :(得分:0)

就像@DanielRearden指出的那样,上下文在调用订阅时为空,这弄乱了我的关系,因为上下文在查询/更改和订阅上的处理方式不同 >。

因此解决了将我的 models 对象添加到ApolloServer中 subscriptions 选项的 onConnect 属性中的问题,并传递了相同的对象已经传递给我的上下文选项

const server = new ApolloServer({
    schema,
    subscriptions: {
        onConnect: () => ({models}),
    },
    context: () => ({models})
}