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

feat(gatsby): provide a mechanism for plugins to use a named cache instance #10146

Merged
merged 8 commits into from
Jan 8, 2019
21 changes: 21 additions & 0 deletions packages/gatsby/src/utils/__tests__/get-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const getCache = require(`../get-cache`)

const CACHE_KEY = `__test__`

test(`it returns a new cache instance`, () => {
const cache = getCache(CACHE_KEY)

expect(cache.get).toEqual(expect.any(Function))
expect(cache.set).toEqual(expect.any(Function))
})

test(`it retrieves already created cache instance`, async () => {
const key = `some-value`
const value = [`a`, `b`, `c`]
const cache = getCache(CACHE_KEY)
await cache.set(key, value)

const other = getCache(CACHE_KEY)

expect(await other.get(key)).toEqual(value)
})
11 changes: 3 additions & 8 deletions packages/gatsby/src/utils/api-runner-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ const _ = require(`lodash`)

const tracer = require(`opentracing`).globalTracer()
const reporter = require(`gatsby-cli/lib/reporter`)
const Cache = require(`./cache`)
const getCache = require(`./get-cache`)
const apiList = require(`./api-node-docs`)
const createNodeId = require(`./create-node-id`)
const createContentDigest = require(`./create-content-digest`)

let caches = new Map()

// Bind action creators per plugin so we can auto-add
// metadata to actions they create.
const boundPluginActionCreators = {}
Expand Down Expand Up @@ -94,11 +92,7 @@ const runAPI = (plugin, api, args) => {

const tracing = initAPICallTracing(pluginSpan)

let cache = caches.get(plugin.name)
if (!cache) {
cache = new Cache({ name: plugin.name }).init()
caches.set(plugin.name, cache)
}
const cache = getCache(plugin.name)

const apiCallArgs = [
{
Expand All @@ -109,6 +103,7 @@ const runAPI = (plugin, api, args) => {
loadNodeContent,
store,
emitter,
getCache,
getNodes,
getNode,
getNodesByType,
Expand Down
12 changes: 12 additions & 0 deletions packages/gatsby/src/utils/get-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const Cache = require(`./cache`)

let caches = new Map()

module.exports = function getCache(name) {
let cache = caches.get(name)
if (!cache) {
cache = new Cache({ name }).init()
caches.set(name, cache)
}
return cache
}