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: support null values #11

Merged
merged 2 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/khaki-falcons-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@labdigital/dataloader-cache-wrapper': minor
---

Properly support caching null values, and dont handle these as missing
4 changes: 2 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

82 changes: 77 additions & 5 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,16 @@ describe('Test keyv store', () => {

const fetchItemsBySlugUncached = async (
keys: readonly MyKey[]
): Promise<(MyValue | Error)[]> =>
keys.map((key) => ({
slug: key.slug,
name: key.slug,
}))
): Promise<(MyValue | null | Error)[]> =>
keys.map((key) => {
if (key.slug.startsWith('null-')) {
return null
}
return {
slug: key.slug,
name: key.slug,
}
})

const loader = new DataLoader<MyKey, any>(fetchItemsBySlug, {
maxBatchSize: 50,
Expand Down Expand Up @@ -135,4 +140,71 @@ describe('Test keyv store', () => {
expect(cachedValue[2].name).toBe('test-2')
}
})

it('Cache missing product', async () => {
const value = await loader.load({
id: '1',
slug: 'test-1',
})
expect(value.slug).toBe('test-1')
expect(value.name).toBe('test-1')

// This should be one cache hit
{
const cachedValue = await loader.loadMany([
{
id: '1',
slug: 'test-1',
},
{
id: '2',
slug: 'test-2',
},
])
expect(cachedValue[0].slug).toBe('test-1')
expect(cachedValue[0].name).toBe('test-1')

expect(cachedValue[1].slug).toBe('test-2')
expect(cachedValue[1].name).toBe('test-2')
}

// This should be two cache hits
{
const cachedValue = await loader.loadMany([
{
id: '1',
slug: 'test-1',
},
{
id: '3',
slug: 'test-3',
},
{
id: '2',
slug: 'test-2',
},
{
id: '4',
slug: 'null-1',
},
])

expect(cachedValue[0].slug).toBe('test-1')
expect(cachedValue[0].name).toBe('test-1')

expect(cachedValue[1].slug).toBe('test-3')
expect(cachedValue[1].name).toBe('test-3')

expect(cachedValue[2].slug).toBe('test-2')
expect(cachedValue[2].name).toBe('test-2')

expect(cachedValue[3]).toBe(null)

const storedNull = await store.get('item-data:4:id:null-1')
expect(storedNull).toBeNull()

const storedUndefined = await store.get('item-data:5:id:null-1')
expect(storedUndefined).toBeUndefined()
}
})
})
28 changes: 16 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ export type cacheOptions<K, V> = {
// Note: this function is O^2, so it should only be used for small batches of
// keys.
export const dataloaderCache = async <K extends NotUndefined, V>(
args: cacheOptions<K, V>
args: cacheOptions<K, V | null>
): Promise<(V | null)[]> => {
const result = await fromCache<K, V>(args.keys, args)
const store: Record<string, V> = {}
const store: Record<string, V | null> = {}

// Check results, if an item is null then it was not in the cache, we place
// these in the cacheMiss array and fetch them.
const cacheMiss: Array<K> = []
for (const [key, cached] of zip(args.keys, result)) {
if (cached === null) {
if (cached === undefined) {
cacheMiss.push(key)
} else {
store[hashObject(key)] = cached
Expand All @@ -41,7 +41,7 @@ export const dataloaderCache = async <K extends NotUndefined, V>(
// next time
if (cacheMiss.length > 0) {
const newItems = await args.batchLoadFn(cacheMiss)
const buffer = new Map<string, V>()
const buffer = new Map<string, V | null>()

zip(cacheMiss, Array.from(newItems)).forEach(([key, item]) => {
if (key === undefined) {
Expand All @@ -58,7 +58,7 @@ export const dataloaderCache = async <K extends NotUndefined, V>(
}
})

await toCache<K, V>(buffer, args)
await toCache<K, V | null>(buffer, args)
}

return args.keys.map((key) => {
Expand All @@ -74,27 +74,31 @@ export const dataloaderCache = async <K extends NotUndefined, V>(
// Read items from the cache by the keys
const fromCache = async <K, V>(
keys: ReadonlyArray<K>,
options: cacheOptions<K, V>
): Promise<(V | null)[]> => {
options: cacheOptions<K, V | null>
): Promise<(V | null | undefined)[]> => {
if (!options.store) {
return new Array<V | null>(keys.length).fill(null)
return new Array<V | null | undefined>(keys.length).fill(undefined)
}

const cacheKeys = keys.flatMap(options.cacheKeysFn)
const cachedValues = await options.store.get(cacheKeys)
return cachedValues.map((v) => v ?? null)
return cachedValues.map((v) => v )
}

// Write items to the cache
const toCache = async <K, V>(
items: Map<string, V>,
options: cacheOptions<K, V>
items: Map<string, V | null>,
options: cacheOptions<K, V | null>
): Promise<void> => {
if (!options.store) {
return
}
for (const [key, value] of items) {
options.store.set(key, value, options.ttl)
options.store.set(
key,
value,
options.ttl
)
}
}

Expand Down
6 changes: 2 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"module": "esnext",
"lib": ["esnext"],
"module": "ES2022",
"allowJs": true,
"importHelpers": true,
"declaration": true,
Expand All @@ -12,8 +11,7 @@
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"moduleResolution": "node",
"jsx": "react",
"moduleResolution": "bundler",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
Expand Down
Loading