Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add real time websocket to apollo graphQl server and client, use subs… #2

Merged
merged 1 commit into from
Apr 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions apollo-graphql/client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apollo-graphql/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"graphql": "^16.6.0",
"graphql-ws": "^5.12.1",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.0",
Expand Down
12 changes: 10 additions & 2 deletions apollo-graphql/client/src/App.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import { useState } from 'react';
import { useQuery, useApolloClient } from '@apollo/client';
import { useQuery, useApolloClient, useSubscription } from '@apollo/client';
import './App.css';
import { ALL_PERSONS } from './queries/queries';
import { ALL_PERSONS, PERSON_ADDED } from './queries/queries';
import { Persons } from './Persons';
import { PersonForm } from './forms/PersonForm';
import { PhoneForm } from './forms/PhoneForm';
import { Notify } from './components/Notify';
import { LoginForm } from './forms/LoginForm';
import { updateCache } from './utils/updateCache';

function App() {
const [token, setToken] = useState(null);
const [errorMsg, setErrorMsg] = useState('');
const result = useQuery(ALL_PERSONS);
const client = useApolloClient();
useSubscription(PERSON_ADDED, {
onData: ({ data }) => {
const addedPerson = data.data.personAdded
notify(`${addedPerson.name} added`)
updateCache(client.cache, { query: ALL_PERSONS }, addedPerson)
}
})

const notify = (message) => {
setErrorMsg(message);
Expand Down
2 changes: 1 addition & 1 deletion apollo-graphql/client/src/forms/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { useMutation } from '@apollo/client';
import { LOGIN } from '../queries';
import { LOGIN } from '../queries/queries';

export const LoginForm = props => {
const [username, setUsername] = useState('');
Expand Down
7 changes: 2 additions & 5 deletions apollo-graphql/client/src/forms/PersonForm.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { useMutation } from '@apollo/client';
import { ALL_PERSONS, ADD_PERSON } from '../queries/queries';
import { updateCache } from '../utils/updateCache';

export const PersonForm = props => {
const [name, setName] = useState('');
Expand All @@ -15,11 +16,7 @@ export const PersonForm = props => {
props.setError(message);
},
update: (cache, response) => {
cache.updateQuery({ query: ALL_PERSONS }, ({ allPersons }) => {
return {
allPersons: allPersons.concat(response.data.addNewPerson),
}
})
updateCache(cache, { query: ALL_PERSONS }, response.data.addPerson)
}
});

Expand Down
9 changes: 4 additions & 5 deletions apollo-graphql/client/src/forms/PhoneForm.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { useState , useEffect } from 'react'
import { useMutation } from '@apollo/client'

import { EDIT_NUMBER } from '../queries'
import { useState , useEffect } from 'react';
import { useMutation } from '@apollo/client';
import { UPDATE_PHONE } from '../queries/queries';

export const PhoneForm = ({ setError }) => {
const [name, setName] = useState('')
const [phone, setPhone] = useState('')

const [ changeNumber, result ] = useMutation(EDIT_NUMBER, {
const [ changeNumber, result ] = useMutation(UPDATE_PHONE, {
onError: (error) => {
const errors = error.graphQLErrors[0].extensions.error.errors
const messages = Object.values(errors).map(e => e.message).join('\n')
Expand Down
22 changes: 20 additions & 2 deletions apollo-graphql/client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@ import {
ApolloClient,
ApolloProvider,
InMemoryCache,
createHttpLink
createHttpLink,
split
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { getMainDefinition } from '@apollo/client/utilities';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';

const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('phonenumbers-user-token')
Expand All @@ -23,9 +27,23 @@ const authLink = setContext((_, { headers }) => {
const httpLink = createHttpLink({
uri: 'http://localhost:4000'
});
const wsLink = new GraphQLWsLink(
createClient({ url: 'ws://localhost:4000' })
);
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
wsLink,
authLink.concat(httpLink)
)

const client = new ApolloClient({
link: authLink.concat(httpLink),
link: splitLink,
cache: new InMemoryCache(),
})

Expand Down
8 changes: 8 additions & 0 deletions apollo-graphql/client/src/queries/queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,11 @@ export const LOGIN = gql`
}
}
`;

export const PERSON_ADDED = gql`
subscription {
personAdded {
${PERSON}
}
}
`;
17 changes: 17 additions & 0 deletions apollo-graphql/client/src/utils/updateCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// function that takes care of manipulating cache
export const updateCache = (cache, query, addedPerson) => {
// helper that is used to eliminate saving same person twice
const uniqByName = (a) => {
let seen = new Set();
return a.filter((item) => {
let k = item.name;
return seen.has(k) ? false : seen.add(k);
});
}
;
cache.updateQuery(query, ({ allPersons }) => {
return {
allPersons: uniqByName(allPersons.concat(addedPerson)),
};
});
};
6 changes: 6 additions & 0 deletions apollo-graphql/server/models/person.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ const schema = new mongoose.Schema({
required: true,
minlength: 3
},
friendOf: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
],
});

module.exports = mongoose.model('Person', schema);
Loading