How to use subscriptions-transport-ws - 10 common examples

To help you get started, we’ve selected a few subscriptions-transport-ws examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mgm-interns / team-radio / backend / src / server.js View on Github external
websocketServer.listen(WS_PORT, () => {
    SubscriptionServer.create(
      {
        execute,
        subscribe,
        schema,
        onConnect: () => ({
          models,
        }),
      },
      {
        server: websocketServer,
        path: '/subscriptions',
      },
    );
    // eslint-disable-next-line no-console
    console.log(
      `App's websocket is listening on port ${websocketServer.address().port}`,
github coralproject / talk / client / coral-framework / services / client.js View on Github external
if (!req.options.headers) {
          req.options.headers = {}; // Create the header object if needed.
        }

        let authToken = resolveToken(token);
        if (authToken) {
          req.options.headers['authorization'] = `Bearer ${authToken}`;
        }
        // To debug queries add print(req.request.query) and import it from graphql/language/printer
        // console.log(print(req.request.query));
        next();
      },
    },
  ]);

  const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
    networkInterface,
    wsClient
  );

  const client = new ApolloClient({
    connectToDevTools: true,
    addTypename: true,
    fragmentMatcher: new IntrospectionFragmentMatcher({
      introspectionQueryResultData: introspectionData,
    }),
    dataIdFromObject: result => {
      if (result.id && result.__typename) {
        // eslint-disable-line no-underscore-dangle
        return `${result.__typename}_${result.id}`; // eslint-disable-line no-underscore-dangle
      }
      return null;
github erxes / erxes-widgets / server / server.js View on Github external
app.listen(GRAPHQL_PORT);

// websocket server
const WS_PORT = settings.WS_PORT;

const httpServer = createServer((request, response) => {
  response.writeHead(404);
  response.end();
});

httpServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console
  `Websocket Server is now running on http://localhost:${WS_PORT}`,
));

// subscription server
const server = new SubscriptionServer( // eslint-disable-line no-unused-vars
  { subscriptionManager },
  httpServer,
);

// receive inAppConnected message and save integrationId, customerId in
// connection
server.wsServer.on('connect', (connection) => {
  connection.on('message', (message) => {
    const parsedMessage = JSON.parse(message.utf8Data);

    if (parsedMessage.type === 'inAppConnected') {
      connection.inAppData = parsedMessage.value; // eslint-disable-line no-param-reassign
    }
  });
});
github janikvonrotz / meteor-apollo-accounts-example / server / main.js View on Github external
// seed the database
seed()
const WS_PORT = process.env.WS_PORT || 8080;

createApolloServer({
  schema: schema,
});

const httpServer = createServer((request, response) => {
  response.writeHead(404);
  response.end();
});
httpServer.listen(WS_PORT, () => console.log(
  `Websocket Server is now running on http://localhost:${WS_PORT}`
));
const server = new SubscriptionServer({ subscriptionManager }, httpServer);
github erxes / erxes-widgets / server / server.js View on Github external
app.listen(GRAPHQL_PORT);

// websocket server
const WS_PORT = settings.WS_PORT;

const httpServer = createServer((request, response) => {
  response.writeHead(404);
  response.end();
});

httpServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console
  `Websocket Server is now running on http://localhost:${WS_PORT}`,
));

// subscription server
const server = new SubscriptionServer( // eslint-disable-line no-unused-vars
  { subscriptionManager },
  httpServer,
);

// receive inAppConnected message and save integrationId, customerId in
// connection
server.wsServer.on('connect', (connection) => {
  connection.on('message', (message) => {
    const parsedMessage = JSON.parse(message.utf8Data);

    if (parsedMessage.type === 'inAppConnected') {
      connection.inAppData = parsedMessage.value; // eslint-disable-line no-param-reassign
    }
  });
});
github notadamking / React-Realtime-Chat / server / server.js View on Github external
models.sequelize.sync({ force: false }).then(() => {
  const server = app.listen(config.server.port, () => {
    console.info(
      `🔌  HTTP and Websocket Server running in ${app.get('env')}`
      + ` on port ${config.server.port}`
    );
  });

  // eslint-disable-next-line
  new SubscriptionServer({ subscriptionManager }, server);
});
github GraphqlBA / codenames-gql / server / index.js View on Github external
// bodyParser is needed just for POST.
app.use('/api/graphql', bodyParser.json(), graphqlExpress({ schema }))
app.use('/api/graphiql', bodyParser.json(), graphiqlExpress({ endpointURL: '/api/graphql' }))

app.listen(PORT)

const websocketServer = createServer((request, response) => {
  response.writeHead(404)
  response.end()
})

websocketServer.listen(WS_PORT, () => console.log(
  `Websocket Server is now running on http://localhost:${WS_PORT}`
))

const subscriptionsServer = new SubscriptionServer(
  {
    subscriptionManager: subscriptionManager
  },
  {
    server: websocketServer
  }
)
github prisma-archive / angular-fullstack-graphql / outdated / subscriptions-with-apollo / src / app / feed.component.ts View on Github external
ngOnInit() {
    const queryObservable = this.apollo.watchQuery({
      query: AllPostsQuery
    })
    this.allPostsSub = queryObservable.subscribe(({data, loading}) => {
      this.allPosts = data.allPosts.reverse();
      this.loading = loading;
    });

    // __SUBSCRIPTIONS_API_ENDPOINT_ looks similar to: `wss://subscriptions.graph.cool/v1/`
    const wsClient = new Client('__SUBSCRIPTIONS_API_ENDPOINT_', {
      timeout: 10000,
      reconnect: true
    })

    wsClient.subscribe({
      query: `subscription {
        Post(filter: {
          mutation_in: [CREATED, UPDATED, DELETED]
        }) {
          node {
            id
            imageUrl
            description
          }
        }
      }`,
github srtucker22 / chatty / client / src / app.js View on Github external
if (_.some(response.errors, { message: 'Unauthorized' })) {
          isUnauthorized = true;
        }
      }
    });

    if (isUnauthorized) {
      store.dispatch(logout());
    }

    next();
  },
}]);

// Create WebSocket client
export const wsClient = new SubscriptionClient(`ws://${URL}/subscriptions`, {
  reconnect: true,
  connectionParams() {
    // get the authentication token from local storage if it exists
    return { jwt: store.getState().auth.jwt };
  },
  lazy: true,
});

// Extend the network interface with the WebSocket
const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
  networkInterface,
  wsClient,
);

export const client = new ApolloClient({
  networkInterface: networkInterfaceWithSubscriptions,
github apollographql / apollo-server / packages / apollo-server-core / src / ApolloServer.ts View on Github external
const { SubscriptionServer } = require('subscriptions-transport-ws');
    const {
      onDisconnect,
      onConnect,
      keepAlive,
      path,
    } = this.subscriptionServerOptions;

    // TODO: This shouldn't use this.schema, as it is deprecated in favor of the schemaDerivedData promise.
    const schema = this.schema;
    if (this.schema === undefined)
      throw new Error(
        'Schema undefined during creation of subscription server.',
      );

    this.subscriptionServer = SubscriptionServer.create(
      {
        schema,
        execute,
        subscribe,
        onConnect: onConnect
          ? onConnect
          : (connectionParams: Object) => ({ ...connectionParams }),
        onDisconnect: onDisconnect,
        onOperation: async (
          message: { payload: any },
          connection: ExecutionParams,
        ) => {
          connection.formatResponse = (value: ExecutionResult) => ({
            ...value,
            errors:
              value.errors &&