Skip to content

Commit

Permalink
feat: support sync cache creation
Browse files Browse the repository at this point in the history
Add non-async `createCache()` that `caching()` uses to set up methods.
  • Loading branch information
denkan committed Sep 29, 2023
1 parent 64e5cce commit 84c0e03
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
35 changes: 28 additions & 7 deletions src/caching.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MemoryCache, MemoryConfig, memoryStore } from './stores';
import { MemoryCache, MemoryConfig, MemoryStore, memoryStore } from './stores';

export type Config = {
ttl?: Milliseconds;
Expand Down Expand Up @@ -62,13 +62,34 @@ export async function caching<S extends Store, T extends object = never>(
export async function caching<S extends Store, T extends object = never>(
factory: Stores<S, T>,
args?: CachingConfig<T>,
): Promise<Cache<S> | MemoryCache> {
let store: Store;
if (factory === 'memory') store = memoryStore(args as MemoryConfig);
else if (typeof factory === 'function')
store = await factory(args as FactoryConfig<T>);
else store = factory;
): Promise<Cache<S> | Cache<Store> | MemoryCache> {
if (factory === 'memory') {
const store = memoryStore(args as MemoryConfig);
return createCache(store, args as MemoryConfig);
}
if (typeof factory === 'function') {
const store = await factory(args as FactoryConfig<T>);
return createCache(store, args);
}

const store = factory;
return createCache(store, args);
}

export function createCache(
store: MemoryStore,
args?: MemoryConfig,
): MemoryCache;

export function createCache(store: Store, args?: Config): Cache<Store>;

/**
* Create cache instance by store (non-async).
*/
export function createCache<S extends Store, C extends Config>(
store: S,
args?: C,
): Cache<S> | MemoryCache {
return {
/**
* Wraps a function in cache. I.e., the first time the function is run,
Expand Down
14 changes: 13 additions & 1 deletion test/caching.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, it, beforeEach, expect, vi } from 'vitest';
import { faker } from '@faker-js/faker';

import { caching, Cache, MemoryConfig, memoryStore } from '../src';
import { caching, Cache, MemoryConfig, memoryStore, createCache } from '../src';
import { sleep } from './utils';

describe('caching', () => {
Expand Down Expand Up @@ -255,3 +255,15 @@ describe('caching', () => {
});
});
});

describe('createCache', () => {
it('should create cache instance by store', async () => {
const store = memoryStore();
const cache1 = await caching(store);
const cache2 = createCache(store);
expect(cache1.store).toBe(cache2.store);
Object.entries(cache1).forEach(([key, value]) => {
expect(cache2[key as keyof Cache].toString()).toBe(value.toString());
});
});
});

0 comments on commit 84c0e03

Please sign in to comment.