javascript React-Native Apollo-client初始化文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript React-Native Apollo-client初始化文件相关的知识,希望对你有一定的参考价值。

import React, { Component } from 'react';
import { ApolloProvider } from 'react-apollo';
import { Font } from 'expo';
import fonts from 'Asset/Font';
import RootContainer from './Root';
import initStore from 'Reduck';
import { initApollo } from 'Configuration';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      apolloClient: undefined,
    };
  }
  async componentDidMount() {
    const promises = await Promise.all([
      initApollo(),
      ...fonts.map(font => Font.loadAsync(font)),
    ]);

    this.setState({
      apolloClient: promises[0],
    });
  }

  render() {
    const { apolloClient } = this.state;
    if (apolloClient !== undefined) {
      return (
        <ApolloProvider client={apolloClient} store={initStore(apolloClient)}>
          <RootContainer />
        </ApolloProvider>
      );
    }
    return null;
  }
}

export default App;
import { ApolloClient, createNetworkInterface } from 'react-apollo';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { addGraphQLSubscriptions } from 'add-graphql-subscriptions';
import { AsyncStorage } from 'react-native';
import { SERVER_ENDPOINT, SERVER_SUBSCRIPTION_ENDPOINT } from 'env';

let apolloClient = null;

const create = async (initialState = {}) => {
  const token = await AsyncStorage.getItem('token');
  const refreshToken = await AsyncStorage.getItem('refreshToken');

  const networkInterface = createNetworkInterface({
    uri: SERVER_ENDPOINT,
    opts: {
      // Additional options like `credentials` or `headers`
    },
  });
  const wsClient = new SubscriptionClient(SERVER_SUBSCRIPTION_ENDPOINT, {
    reconnect: true,
    connectionParams: {
      authToken: token,
      refreshToken: refreshToken,
    },
  });
  networkInterface.use([
    {
      applyMiddleware: async (req, next) => {
        if (!req.options.headers) {
          req.options.headers = {}; // Create the header object if needed.
        }

        const token = await AsyncStorage.getItem('token');
        const refreshToken = await AsyncStorage.getItem('refreshToken');
        req.options.headers.authorization = token;
        req.options.headers.refreshToken = refreshToken;
        next();
      },
    },
  ]);
  networkInterface.useAfter([
    {
      applyAfterware: ({ response }, next) => {
        response
          .clone()
          .json()
          .then(res => {
            if (res.errors && res.errors[0].message === 'unauthorized') {
              AsyncStorage.multiRemove(['id', 'token', 'refreshToken']).then(
                next,
              );
            }
          });
        const token = response.headers.get('X-Token');
        const refreshToken = response.headers.get('X-Refresh-Token');
        if (token && refreshToken) {
          AsyncStorage.multiSet([
            ['token', token],
            ['refreshToken', refreshToken],
          ]).then(next);
        } else {
          next();
        }
      },
    },
  ]);

  const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
    networkInterface,
    wsClient,
  );
  return new ApolloClient({
    initialState,
    networkInterface: networkInterfaceWithSubscriptions,
  });
};

export default async () => {
  if (!apolloClient) {
    apolloClient = await create(undefined);
  }
  return apolloClient;
};

以上是关于javascript React-Native Apollo-client初始化文件的主要内容,如果未能解决你的问题,请参考以下文章

React-native:从 javascript 迁移到 typescript

javascript 基本的React-Native组件

使用react-native做一个简单的应用-01项目介绍

react-native 应用程序是不是应该针对 JavaScript 的特定版本或子集?

从 Javascript 调用包装器函数会导致应用程序崩溃 - React-Native

Firebase:通过设备 ID 向 JavaScript 客户端(react-native)发送消息