Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Commit

Permalink
feat(cache): Align @Cache to match Zapper API (#755)
Browse files Browse the repository at this point in the history
  • Loading branch information
JForsaken authored Jun 26, 2022
1 parent 618d7f4 commit f0b5cd7
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions src/cache/cache.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,50 @@
import { applyDecorators, SetMetadata } from '@nestjs/common';
import { ClassConstructor } from 'class-transformer';

export const CACHE_KEY = 'CACHE_KEY';
export const CACHE_TTL = 'CACHE_TTL';
export const CACHE_INSTANCE = 'CACHE_INSTANCE';
const CACHE_FAIL_ON_MISSING_CACHE = 'CACHE_FAIL_ON_MISSING_CACHE';
export const CACHE_TTL = 'CACHE_TTL';
export const CACHE_LOCAL_TTL = 'CACHE_LOCAL_TTL';
export const CACHE_FORCE_UPDATE = 'CACHE_FORCE_UPDATE';
export const CACHE_DESERIALIZE_INTO = 'CACHE_DESERIALIZE_INTO';
export const CACHE_SHOULD_CACHE_NULL = 'CACHE_SHOULD_CACHE_NULL';

type DeserializeIntoArray<T = unknown> = [ClassConstructor<T>];
type DeserializeInto<T = unknown> = DeserializeIntoArray<T> | ClassConstructor<T>;

type CacheKeyBuilder = (...args: any) => string;
type CacheTtlBuilder = (...args: any) => number;
type CacheForceUpdateBuilder = (...args: any) => boolean;

export type CacheOptions = {
instance?: 'user' | 'business';
key: string | CacheKeyBuilder;
/** In seconds */
ttl?: number | null | CacheTtlBuilder;
instance?: 'business' | 'user';
failOnMissingData?: boolean;
/** In seconds */
localTtl?: number | null | CacheTtlBuilder;
forceUpdate?: boolean | CacheForceUpdateBuilder;
deserializeInto?: DeserializeInto;
cacheNull?: boolean;
};

export const Cache = (options: CacheOptions) => {
const { failOnMissingData = false, ttl = null, instance = 'business' } = options;
const {
ttl = null,
instance = 'business',
localTtl = null,
forceUpdate = false,
deserializeInto = undefined,
cacheNull = false,
} = options;

return applyDecorators(
SetMetadata(CACHE_KEY, options.key),
SetMetadata(CACHE_INSTANCE, instance),
SetMetadata(CACHE_TTL, ttl),
SetMetadata(
CACHE_FAIL_ON_MISSING_CACHE,
// Do not throw locally if cached data is missing, try to fetch it
// to ease development
process.env.NODE_ENV !== 'production' ? failOnMissingData : false,
),
SetMetadata(CACHE_LOCAL_TTL, localTtl),
SetMetadata(CACHE_FORCE_UPDATE, forceUpdate),
SetMetadata(CACHE_DESERIALIZE_INTO, deserializeInto),
SetMetadata(CACHE_SHOULD_CACHE_NULL, cacheNull),
);
};

0 comments on commit f0b5cd7

Please sign in to comment.