Skip to content

Instantly share code, notes, and snippets.

@douglasnomizo
Created December 14, 2018 13:44
Show Gist options
  • Save douglasnomizo/f5a6f657f3692091f8b755000e327a33 to your computer and use it in GitHub Desktop.
Save douglasnomizo/f5a6f657f3692091f8b755000e327a33 to your computer and use it in GitHub Desktop.
// This Gist doesn't work with Graphql because of the deep nature of "selections" object
import { get } from 'lodash'
const memoizedResults = {}
export default (serializer: string, fn: Function): Function => async (
...args: Array<any>
): Promise<Object> => {
const [serializable, selections] = args
const identifier = get(serializable, 'id', get(serializable, 'uid'))
const memoized = get(memoizedResults, `${serializer}.${identifier}`)
const existingSelection = get(memoizedResults, `${serializer}.${identifier}.selections`, [])
const hasSelection = selections === existingSelection
if (memoized && hasSelection) {
return get(memoizedResults, `${identifier}.data`)
}
const data = await fn(...args)
memoizedResults[serializer] = {
...memoizedResults[serializer],
[identifier]: {
data,
selections,
},
}
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment