stacker.news/lib/apollo.js

87 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-09-07 20:22:57 +00:00
import { ApolloClient, InMemoryCache, from, HttpLink } from '@apollo/client'
import { decodeCursor, LIMIT } from './cursor'
2021-09-07 20:22:57 +00:00
import { RetryLink } from '@apollo/client/link/retry'
const additiveLink = from([
new RetryLink(),
new HttpLink({ uri: '/api/graphql' })
])
2021-10-26 20:49:37 +00:00
function isFirstPage (cursor, existingThings) {
if (cursor) {
const decursor = decodeCursor(cursor)
return decursor.offset === LIMIT
} else {
// we don't have anything cached, or our existing items are less than
2021-09-30 15:46:58 +00:00
// or equal to a full page
2021-10-26 20:49:37 +00:00
return existingThings?.length < LIMIT
}
}
2021-09-30 15:46:58 +00:00
export default function getApolloClient () {
global.apolloClient ||= new ApolloClient({
link: additiveLink,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
moreItems: {
2021-10-26 20:49:37 +00:00
keyArgs: ['sort', 'name', 'within'],
2021-09-30 15:46:58 +00:00
merge (existing, incoming) {
2021-10-26 20:49:37 +00:00
if (isFirstPage(incoming.cursor, existing?.items)) {
2021-09-30 15:46:58 +00:00
return incoming
}
2021-09-30 15:46:58 +00:00
return {
cursor: incoming.cursor,
items: [...(existing?.items || []), ...incoming.items]
}
}
2021-09-30 15:46:58 +00:00
},
moreFlatComments: {
2021-10-26 20:49:37 +00:00
keyArgs: ['name'],
2021-09-30 15:46:58 +00:00
merge (existing, incoming) {
2021-10-26 20:49:37 +00:00
if (isFirstPage(incoming.cursor, existing?.comments)) {
2021-09-30 15:46:58 +00:00
return incoming
}
2021-09-30 15:46:58 +00:00
return {
cursor: incoming.cursor,
comments: [...(existing?.comments || []), ...incoming.comments]
}
}
2021-09-30 15:46:58 +00:00
},
notifications: {
keyArgs: false,
merge (existing, incoming) {
2021-10-26 20:49:37 +00:00
if (isFirstPage(incoming.cursor, existing?.notifications)) {
2021-09-30 15:46:58 +00:00
return incoming
}
2021-09-30 15:46:58 +00:00
return {
cursor: incoming.cursor,
notifications: [...(existing?.notifications || []), ...incoming.notifications],
lastChecked: incoming.lastChecked
}
}
}
}
}
}
2021-09-30 15:46:58 +00:00
}),
defaultOptions: {
// cache-and-network allows us to refresh pages on navigation
watchQuery: {
2021-10-26 20:49:37 +00:00
fetchPolicy: 'cache-only',
2021-09-30 15:46:58 +00:00
nextFetchPolicy: 'cache-first'
},
query: {
2021-10-26 20:49:37 +00:00
fetchPolicy: 'cache-only',
2021-09-30 15:46:58 +00:00
nextFetchPolicy: 'cache-first'
}
}
2021-09-30 15:46:58 +00:00
})
return global.apolloClient
}