While working on my latest project, an Instagram clone, I made use of GraphQL subscriptions to implement the functionality for liking/unliking posts. For my client, I utilized npx create-react-app
to set up the front end and express
for the server.
Within the client side code, I structured my client
as follows:
src/apis/client.js
import {
ApolloClient,
ApolloLink,
HttpLink,
InMemoryCache,
split,
} from 'apollo-boost';
import {getMainDefinition} from '@apollo/client/utilities';
import {WebSocketLink} from '@apollo/client/link/ws';
const httpUrl = 'http://localhost:5000/graphql';
const wsUrl = 'ws://localhost:5000/graphql';
const httpLink = ApolloLink.from([
new ApolloLink((operation, forward) => {}),
new HttpLink({uri: httpUrl}),
]);
const wsLink = new WebSocketLink({
uri: wsUrl,
options: {
// connectionParams: () => {},
lazy: true,
reconnect: true,
},
});
function isSubscription(operation) {
const definition = getMainDefinition(operation.query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
}
const client = new ApolloClient({
cache: new InMemoryCache(),
link: split(isSubscription, wsLink, httpLink),
defaultOptions: {query: {fetchPolicy: 'no-cache'}},
});
export default client;
Initially, I only used HTTP connection and everything ran smoothly. However, I later integrated websocket connection into my project as well.
Onto the server side, the setup in my app.js
file is as follows:
const {ApolloServer, gql} = require('apollo-server-express');
const http = require('http');
const fs = require('fs');
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors(), bodyParser.json());
const typeDefs = gql(fs.readFileSync('./schema.graphql', {encoding: 'utf8'}));
const resolvers = require('./resolvers');
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
});
apolloServer.applyMiddleware({app, path: '/graphql'});
const httpServer = http.createServer(app);
apolloServer.installSubscriptionHandlers(httpServer);
const port = 5000;
httpServer.listen(port, () => console.log(`Server started on port ${port}`));
The current issue I am facing can be seen here: https://i.sstatic.net/s5Zeb.png
After researching, it appears to be related to a aspect within the React webpack.config file. Unfortunately, I am not well-versed in webpack configurations. Any guidance on how to resolve this would be greatly appreciated. Thank you and have a wonderful day!