下面是我的graphqlClient.ts
文件:
import {
ApolloClient,
HttpLink,
ApolloLink,
InMemoryCache,
concat,
Operation,
NextLink,
FetchResult,
Observable,
split,
} from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth';
import Config from 'react-native-config';
const httpLink = new HttpLink({ uri: Config.BE_BASE_URL });
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
const wsLink = new GraphQLWsLink(
createClient({
url: 'ws://my-gqlserver.railway.app/graphql',
}),
);
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
const authMiddleware = new ApolloLink(
(operation: Operation, forward: NextLink): Observable<FetchResult> => {
return new Observable(observer => {
(async () => {
const currentUser: FirebaseAuthTypes.User | null = auth().currentUser;
const token = currentUser ? await currentUser.getIdToken(false) : null;
operation.setContext({
headers: {
Authorization: token ? `Bearer ${token}` : '',
},
});
return forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})();
});
},
);
const graphQLClient = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, splitLink),
});
export default graphQLClient;
字符串
下面是查询:
export const SUBSCRIBE_TO_LOCATIONS = gql`
subscription Subscription {
locations
}
`;
型
在主屏幕上,我使用@apollo/client
中的useSubscription
挂钩HomeScreen.tsx
:
import { useSubscription, useQuery } from '@apollo/client';
import { SUBSCRIBE_TO_LOCATIONS } from '../graphql/queries';
const { data: subscriptionData, loading: subscritionLoading } =
useSubscription(SUBSCRIBE_TO_LOCATIONS, {
onData: subData => {
console.log('onData', subData);
},
});
console.log(subscriptionData, 'subscriptionData');
// iOS ==> undefined subscriptionData
// android ==> array of coordinates
型
我做的一切都是从官方文档开始的,对于websocekt协议,我使用graphql-ws
,因为subscriptions-transport-ws
已经过时了,正如文档中提到的那样。
我很确定一切都连接得很好,因为在android上它应该如何工作,所以我猜是有一些elese我需要在ios上配置,但我不确定是什么。
1条答案
按热度按时间gupuwyp21#
很抱歉这个来得晚了,但我最近也遇到了类似的问题;
改变这种
字符串
本
型
基本上,我们正在将不安全的
ws://
更改为安全的wss://
。iOS不允许从http
或ws
上的不安全链接加载,而不是https
或wss
。您可以通过编辑info.plist的传输安全密钥来覆盖此行为(或类似的东西),但我猜你是在世博会的管理工作流,它可能很难做到这一点,除非你弹出或切换到裸露的工作流。干杯