Skip to content

Commit

Permalink
feat(cache): allow default options at service level
Browse files Browse the repository at this point in the history
  • Loading branch information
CarsonF committed Sep 23, 2024
1 parent b4570a4 commit 2a60fb2
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions packages/cache/src/cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,44 @@ import '@seedcompany/common/temporal/luxon';

@Injectable()
export class CacheService {
constructor(private readonly store: CacheStore) {}
constructor(
private readonly store: CacheStore,
private readonly defaultOptions?: StoreItemOptions,
) {}

get adaptTo() {
return new CacheAdapters(this);
}

namespace(subSpace: string) {
withDefaultOptions(options: ItemOptions) {
return new CacheService(this.store, resolveOptions(options));
}

namespace(subSpace: string, defaultOptions?: ItemOptions) {
if (!subSpace) {
return this;
}
return new CacheService(new NamespaceStore(this.store, subSpace));
return new CacheService(
new NamespaceStore(this.store, subSpace),
defaultOptions ? resolveOptions(defaultOptions) : undefined,
);
}

item<T>(key: string, options?: ItemOptions): CacheItem<T> {
return new CacheItem<T>(key, this, options ? resolveOptions(options) : {});
}

async get<T>(key: string, options: ItemOptions = {}): Promise<T | undefined> {
return await this.store.get<T>(key, resolveOptions(options));
return await this.store.get<T>(key, this.resolveOptions(options));
}

async set(key: string, value: unknown, options: ItemOptions = {}) {
await this.store.set(key, value, resolveOptions(options));
await this.store.set(key, value, this.resolveOptions(options));
}

private resolveOptions(options: ItemOptions) {
const opts = resolveOptions(options);
return this.defaultOptions ? { ...this.defaultOptions, ...opts } : opts;
}

async delete(key: string) {
Expand Down

0 comments on commit 2a60fb2

Please sign in to comment.