Skip to content

Instantly share code, notes, and snippets.

@codeartistryio
Created September 4, 2020 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeartistryio/5fb37e06fd04caaba376bbfea8600c5b to your computer and use it in GitHub Desktop.
Save codeartistryio/5fb37e06fd04caaba376bbfea8600c5b to your computer and use it in GitHub Desktop.
graphql/client.js
import ApolloClient from "apollo-client";
import { WebSocketLink } from "apollo-link-ws";
import { InMemoryCache } from "apollo-cache-inmemory";
import gql from "graphql-tag";
import { GET_QUEUED_SONGS } from "./queries";
// const httpurl = "https://hasura-insta.herokuapp.com/v1/graphql";
const wsurl = "wss://react-music-share.herokuapp.com/v1/graphql";
const headers = { "x-hasura-admin-secret": "V_'P8nVU" };
const client = new ApolloClient({
link: new WebSocketLink({
uri: wsurl,
options: {
reconnect: true,
connectionParams: {
headers
}
}
}),
cache: new InMemoryCache(),
typeDefs: gql`
type Query {
queue: [Song]
}
type Song {
duration: Float!
artist: String!
thumbnail: String!
title: String!
url: String!
}
input SongInput {
duration: Float!
artist: String!
thumbnail: String!
title: String!
url: String!
}
type Mutation {
addOrRemoveFromQueue(input: SongInput): [Song]!
}
`,
resolvers: {
Mutation: {
addOrRemoveFromQueue: (_, { input }, { cache }) => {
// console.log(input, cache);
const queryResult = cache.readQuery({
query: GET_QUEUED_SONGS
});
if (queryResult) {
const { queue } = queryResult;
const newQueue = queue.some(song => song.url === input.url)
? queue.filter(song => song.url !== input.url)
: [...queue, input];
// console.log(newQueue);
cache.writeQuery({
query: GET_QUEUED_SONGS,
data: { queue: newQueue }
});
return newQueue;
}
return [];
}
}
}
});
const hasQueue = Boolean(localStorage.getItem("queue"));
const data = {
queue: hasQueue ? JSON.parse(localStorage.getItem("queue")) : []
};
console.log({ data });
// write the cache data on initial load
client.writeData({ data });
// write the cache data after cache is reset
// client.onResetStore(() => client.writeData({ data }));
export default client;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment