通过 GRAPHQL 订阅传递数据仅在其中一个参数上给出 null

2023-12-06

我有以下 GRAPHQL 订阅:

Schema.graphql
    type Subscription {
      booking: SubscriptionData
    }

    type SubscriptionData {
      booking: Booking!
      action: String
    }

这是解析器订阅文件

Resolver/Subscription.js
const Subscription = {
  booking: {
    subscribe(parent, args, { pubsub }, info) {
      return pubsub.asyncIterator("booking");
    }
  }
};

export default Subscription;

然后我对相关的突变有以下代码

pubsub.publish("booking", { booking: { booking }, action: "test" });

我在前端有以下订阅文件(React)

const getAllBookings = gql`
  query {
    bookings {
      time
      durationMin
      payed
      selected
      activity {
        name
      }
    }
  }
`;

const getAllBookingsInitial = {
  query: gql`
    query {
      bookings {
        time
        durationMin
        payed
        selected
        activity {
          name
        }
      }
    }
  `
};

class AllBookings extends Component {
  state = { allBookings: [] }

  componentWillMount() {
    console.log('componentWillMount inside AllBookings.js')
    client.query(getAllBookingsInitial).then(res => this.setState({ allBookings: res.data.bookings })).catch(err => console.log("an error occurred: ", err));
  }

  componentDidMount() {
    console.log(this.props.getAllBookingsQuery)
    this.createBookingsSubscription = this.props.getAllBookingsQuery.subscribeToMore(
      {
        document: gql`
          subscription {
            booking {
              booking { 
                time
                durationMin
                payed
                selected
                activity {
                  name
                   }
              }
              action
            }
          }
        `,
        updateQuery: async (prevState, { subscriptionData }) => {
          console.log('subscriptionData', subscriptionData)
          const newBooking = subscriptionData.data.booking.booking;
          const newState = [...this.state.allBookings, newBooking]
          this.setState((prevState) => ({ allBookings: [...prevState.allBookings, newBooking] }))
          this.props.setAllBookings(newState);
        }
      },
      err => console.error(err)
    );
  }
  render() {
    return null;
  }
}

export default graphql(getAllBookings, { name: "getAllBookingsQuery" })(
  AllBookings
);

我得到以下回复:

data: {
booking: {booking: {...} action: null}}

我知道我可能以某种方式设置了错误的订阅,但我没有看到这个问题。


根据您的架构,所需的data返回的应该是这样的:

{
  "booking": {
    "booking": {
      ...
    },
    "action": "test"
  }
}

首先booking该字段是否处于Subscription,而第二个预订是 SubscriptionData 上的字段。您传递给的对象publish应具有相同的形状(即它应始终包含根级订阅字段)。

pubsub.publish('booking', {
  booking: {
    booking,
    action: 'test',
  },
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 GRAPHQL 订阅传递数据仅在其中一个参数上给出 null 的相关文章

随机推荐