apollographql / apollo-link

:link: Interface for fetching and modifying control flow of GraphQL requests
https://www.apollographql.com/docs/link/
MIT License
1.44k stars 344 forks source link

this.wsImpl is not a constructor and Unable to find native implementation, or alternative implementation for WebSocket! in subscription client in apollo subscription #644

Open anikethsaha opened 6 years ago

anikethsaha commented 6 years ago

I am writing graphql subscription using apollo-client and link packages . the server working fine but the client not . My client

import { split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory';
import { SubscriptionClient } from "subscriptions-transport-ws";

const WebSocket = require('isomorphic-ws')

const ws = new WebSocket('ws://localhost:3000/subscriptions', {
  origin: 'http://localhost:3000/graphql'
});

// Create an http link:
const httpLink = new HttpLink({
  uri: 'http://localhost:3000/graphql'
});

const GRAPHQL_ENDPOINT = "ws://localhost:3000/subscriptions";

const wsClient = new SubscriptionClient(GRAPHQL_ENDPOINT, {
  reconnect: true
},ws);

const wsLink = new WebSocketLink(wsClient);

const link = split(

  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink,
);
const cache = new InMemoryCache();
export const client = new ApolloClient({
  link,
  cache
});

Now I am error

Unable to find native implementation, or alternative implementation for WebSocket! in subscription client in apollo subscription

after some searching I added the ws from ws package also but it seems that ws package is having there own wierd problem like cannot find fs ,net etc. which are the default node packages. Now there is nothing mentioned about adding any websockets in the apollo docs then why this error is coming? help me here In the last I change the ws with isomorphic-ws and now the coming is

this.client = new this.wsImpl(this.url, protocol_1.GRAPHQL_WS); ^

TypeError: this.wsImpl is not a constructor

mluis commented 4 years ago

+1 on this

whalelephant commented 4 years ago

+1

whalelephant commented 4 years ago

Found that if you use this websocket client, you can create a ApolloClient with subscription

const WebSocket = require('websocket').client;
...
  const wsLink = new WebSocketLink({
    uri: WS_URI,
    options: {
      reconnect: true,
    },
    webSocketImpl: WebSocket
  });