Skip to content

Instantly share code, notes, and snippets.

@sebas5384
Last active May 2, 2019 17:33
Show Gist options
  • Save sebas5384/65189cd38dbd97bd823f4c95c45ba9b3 to your computer and use it in GitHub Desktop.
Save sebas5384/65189cd38dbd97bd823f4c95c45ba9b3 to your computer and use it in GitHub Desktop.
import { split, pipe, concat, uniq, join } from "ramda"
import { isDevelopment, isClient } from "app/lib/func"
// During development, use Drupal's own cache-tags header.
const headerName = isDevelopment() ? "X-Drupal-Cache-Tags" : "Cache-Tag"
const separator = isDevelopment() ? " " : ","
const splitTags = split(separator)
const mergeTags = pipe(
concat,
uniq,
join(separator)
)
/**
* Cache Tags middleware.
* @param {Object} context
*/
export const extractCacheTags = context => fetcher => (...args) =>
fetcher(...args).then(response => {
// Short exit on client or when no response is available (SSR).
if (isClient() || !context.res) return response
// Short exit if no cache-tags are found on the response.
if (!response.headers.has(headerName)) return response
// Get header current raw value
const currentValue = context.res.get(headerName)
// Get an array of current cache-tags.
const tagsBuffer = currentValue ? splitTags(currentValue) : []
// Get new cache tags.
const newTags = splitTags(response.headers.get(headerName))
// Construct new value for the header combining new tags to old ones.
const newHeader = mergeTags(tagsBuffer, newTags)
// Save the new hader value to the server response.
context.res.set(headerName, newHeader)
return response
})
import fetch from "isomorphic-fetch"
import { createHttpLink } from "apollo-link-http"
import { ApolloClient } from "apollo-client"
import { InMemoryCache } from "apollo-cache-inmemory"
import { isDevelopment, isClient } from "app/lib/func"
import { extractCacheTags } from "app/lib/cacheTagsAfterware"
const createLink = context => {
const cacheTagExtractor = extractCacheTags(context) // Create an extractor with the `context` from nextjs.
const httpLinkGET = createHttpLink({
uri: GRAPHQL_HOST,
fetch: cacheTagExtractor(fetch) // Compose fetch to extract cache tags at each request.
})
}
/**
* Creates a new ApolloClient instance.
*/
const create = ({ context, initialState = {}, cacheOptions = {} }) =>
new ApolloClient({
connectToDevTools: isClient() && isDevelopment(),
ssrMode: isServer(), // Disables forceFetch on the server (so queries are only run once)
link: createLink(context), // Create apollo-link with `context` fron getInitialProps() on nextjs.
cache: new InMemoryCache({
...defaultCacheOptions,
...cacheOptions
}).restore(initialState)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment