Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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}`,
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;
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
}
});
});
// 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);
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
}
});
});
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);
});
// 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
}
)
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
}
}
}`,
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,
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 &&