反应本机订阅错误:{消息:“无法读取未定义的属性'split'”}

时间:2019-06-22 16:11:34

标签: react-native graphql apollo-client

enter image description here我不知道为什么订阅会弹出此消息(消息:“无法读取未定义的属性'split'”)。要访问graphql操场上的订阅,就可以了。但这最终导致了对本机反应的问题。而且它也没有给我足够的信息来找出哪一部分出错了。它仅给出未定义的拆分。未定义拆分是来自标记的错误日志。

这里是巧妙的设置

import { ApolloLink } from "apollo-link";
import { WebSocketLink } from "apollo-link-ws";
import {
  ApolloClient,
  HttpLink,
  InMemoryCache,
  split
} from "apollo-client-preset";
import moment from "moment-timezone";
import apolloLogger from "apollo-link-logger";
import { getMainDefinition } from "apollo-utilities";
import {
  createHttpLink,
  cache,
  errorLink,
  authLink,
  tokenRefreshLink,
  createSubscriptionLink
} from "./links";
import { resolvers, typeDefs } from "./resolvers";
import { createUploadLink } from "apollo-upload-client";

let host = "http://localhost:4000";
let mediaHost = "http://localhost:2999";
let subscriptionHost = "ws://localhost:4000";

// Default http link for Queries / Mutations
const defaultLink = createHttpLink(host);

// HTTP Link for Upload mutations
const mediaLink = createUploadLink({ uri: mediaHost });

// Websocket / subscription link
const subscriptionLink = createSubscriptionLink(subscriptionHost);

const httpLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    const operationName = definition.name.value;
    const uploadMutationNames = ["uploadRawUserImage"];
    return (
      definition.operation === "mutation" &&
      uploadMutationNames.includes(operationName)
    );
  },
  mediaLink,
  defaultLink
);

const transportLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  subscriptionLink,
  httpLink
);

const client = new ApolloClient({
  cache,
  link: ApolloLink.from([
    split(op => !op.getContext().doNotLog, apolloLogger),
    errorLink,
    authLink,
    errorLink,
    tokenRefreshLink,
    transportLink
  ]),
  resolvers,
  typeDefs
});

let timezone;
try {
  timezone = DeviceInfo.getTimezone();
} catch (e) {
  timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
}
moment.tz.setDefault(timezone);

let weekStart = moment(
  moment(new Date(), null, timezone)
    .startOf("day")
    .utc(),
  moment.ISO_8601
).format();

let weekEnd = moment(
  moment(new Date(), null, timezone)
    .add(1, "w")
    .endOf("day")
    .utc(),
  moment.ISO_8601
).format();

cache.writeData({
  data: {
    userGender: "",
    eventCreation: {
      selectedUserId: null,
      selectedVenueId: null,
      dateTime: null,
      __typename: "EventCreation"
    },
    userDiscoveryFilters: {
      genders: ["MALE", "FEMALE"],
      age: {
        min: 18,
        max: 75,
        __typename: "AgeRange"
      },
      __typename: "UserDiscoveryFilters"
    },
    eventFeed: {
      displayOptions: {
        orderBy: "Date",
        startOfWeek: weekStart,
        endOfWeek: weekEnd,
        selectedDate: moment(new Date()).date(),
        __typename: "EventFeedDisplayOptions"
      },
      viewedEventId: null,
      __typename: "EventFeed"
    },
    eventsOrder: {
      orderBy: "Date",
      __typename: "EventsOrder"
    },
    temporaryOnboardingData: {
      email: null,
      phone: null,
      __typename: "TemporaryOnboardingData"
    },
    permissions: [{ name: "location", value: true, __typename: "Permission" }],
    isSwipeable: true
  }
});

export default client;

// import { HttpLink } from "apollo-link-http";
import { ApolloClient, HttpLink, InMemoryCache } from "apollo-client-preset";

const createHttpLink = (host, fetch) => new HttpLink({ uri: host, fetch });

export default createHttpLink;

import { WebSocketLink } from "apollo-link-ws";
import { SubscriptionClient } from "subscriptions-transport-ws";
import { AsyncStorage } from "react-native";

export const createSubscriptionLink = uri => {
  const subscriptionClient = new SubscriptionClient(uri, {
    reconnect: true,
    connectionParams: () => ({
      authorization: `Bearer ${AsyncStorage.getItem("accessToken")}`
    })
  });

  subscriptionClient.connectionCallback = err => {
    if (err.message === "Authentication Failure!") {
      subscriptionClient.close();
    }
  };

  return new WebSocketLink(subscriptionClient);
};

import { ApolloClient, HttpLink, InMemoryCache } from "apollo-client-preset";

const cache = new InMemoryCache({
  cacheRedirects: {
    Query: {
      venue: (_, { where: { id } }, { getCacheKey }) =>
        getCacheKey({ __typename: "Venue", id: id }),
      event: (_, { where: { id } }, { getCacheKey }) =>
        getCacheKey({ __typename: "Event", id: id }),
      user: (_, { where: { id } }, { getCacheKey }) =>
        getCacheKey({ __typename: "User", id: id })
    }
  }
});
export default cache;

在这里我称为订阅

  render() {
    return (
      <Subscription
        subscription={gql`
          subscription {
            Preselection {
              node {
                id
                selected {
                  id
                }
              }
              mutation
            }
          }
        `}
        context={{ doNotLog: false }}
      >
        {({ data, loading, error }) => {
          if (loading) {
            return <Text>{"Loading..."}</Text>;
          }
          if (error) {
            console.log("PRESELECTION_SUBSCRIPTION error:", error);
            return <Text>{"Error..."}</Text>;
          }

          return <Text>{"PRESELECTION_SUBSCRIPTION"}</Text>;
        }}
      </Subscription>
    );
  }

,浏览器控制台上的错误消息如下: PRESELECTION_SUBSCRIPTION错误:{消息:“无法读取未定义的属性'split'”}

0 个答案:

没有答案