[获得的数据在apollo客户端/ apollo服务器和useSubscription中仅为空

问题描述 投票:1回答:1

我尝试在apollo服务器和apollo客户端中使用pubsub。但订阅的数据仅为null。

客户端依赖性

 "@apollo/react-hooks": "^3.1.5",
 "apollo-boost": "^0.4.9",
 "apollo-link-ws": "^1.0.20",
 "graphql": "^15.0.0",
 "react": "^16.13.1",
 "react-dom": "^16.13.1",
 "react-router-dom": "^5.2.0",
 "react-scripts": "3.4.1",
 "styled-components": "^5.1.1",
 "subscriptions-transport-ws": "^0.9.16",
 "typescript": "~3.7.2"

服务器依赖性

  "apollo-server": "^2.14.1",
  "graphql": "^15.0.0",
  "merge-graphql-schemas": "^1.7.8",
  "ts-node": "^8.10.2",
  "tsconfig-paths": "^3.9.0",
  "typescript": "^3.9.3"

// apolloClient.ts

import { ApolloClient, HttpLink, InMemoryCache, split } from 'apollo-boost'

import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'

const wsLink = new WebSocketLink({
  uri: 'ws://localhost:4000/graphql',
  options: {
    reconnect: true
  }
})

const httpLink = new HttpLink({
  uri: 'http://localhost:4000'
})

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
)

const cache = new InMemoryCache()
const client = new ApolloClient({
  cache: cache,
  link: link,
})

export default client

// subscribe.ts

const ON_PUT_UNIT = gql`
  subscription onPutUnit($code: String!) {
    onPutUnit(code: $code)
  }
`
const onPutResult = useSubscription(
    ON_PUT_UNIT,
    { variables: {
      code: code,
    }}
  )

// in is only null!!
console.log('subscribe', onPutResult)

-服务器-onPutUnit.ts

type Subscription {
  onPutUnit(code: String!): Room
}

import { pubsub } from '@src/index'
const { withFilter } = require('apollo-server')
export default {
  Subscription: {
    onPutUnit: {
      subscribe: withFilter(
       () => pubsub.asyncIterator(['PUT_UNIT']),
       (payload: any, variables: any) => {
         // no problem in payload & variable data 
         return payload.code === variables.code
       }
      ) 
    }
  },
}

putUnit.ts

type Mutation {
  putUnit(code: String!, x: Int!, y: Int!, userName: String!): Room!
}

export default {
  Mutation: {
    putUnit: async (_: any, args: args) => {
      const { code, x, y, userName } = args
      const room = findRoom(code)
      console.log(room) // no problem. normal data.
      pubsub.publish('PUT_UNIT', room)
      return room
    },
  },
}

有什么问题吗?订阅事件通常在发布时到达客户端。但数据仅为空。我无法解释原因。

apollo publish-subscribe apollo-client apollo-server
1个回答
0
投票

您只为subscribe指定了onPutUnit功能,而没有指定resolve功能。这意味着该字段使用默认的解析器。

© www.soinside.com 2019 - 2024. All rights reserved.