Skip to content

v3.0.0

Latest
Compare
Choose a tag to compare
@anchan828 anchan828 released this 20 Jul 17:02
· 196 commits to main since this release

Features

Added a new CacheMiddleware

You can add middleware that is executed just before calling the cache method. It can be used as an interceptor to process the cache key or the value to be stored, or to define dependencies on the cache to manipulate other caches under certain conditions.

@Injectable()
export class ExampleService {
  constructor(private readonly cacheService: CacheService) {}

  public async update(userId: number, age: number): Promise<void> {
    await this.cacheService.set(`users/${userId}`, age, 10, {
      /**
       * You can pass information to be processed under specific conditions used in middleware.
       */
      source: { userId },
    });
  }
}

@CacheMiddleware({
  /**
   * The priority of the middleware. The higher the number, the low the priority.
   */
  priority: 1,
})
class TestCacheMiddleware implements ICacheMiddleware {
  constructor(private readonly cacheService: CacheService) {}
  /**
   * If you want to set a hook for set, implement the set method.
   */
  async set(context: CacheContext<"set">): Promise<void> {
    /**
     * Change data
     */
    context.key = `version-1/${context.key}`;
    context.value = { data: context.value };
    context.ttl = 1000;

    /**
     * Get the source passed from the set method
     */
    const source = context.getSource<{ userId: number }>();

    /**
     * Manage other caches under certain conditions
     */
    if (source?.userId === 1) {
      this.cacheService.delete("another-cache-key");
    }
  }

  /**
   * You can define middleware for most methods.
   */
  // ttl?(context: CacheContext<"ttl">): Promise<void>;
  // delete?(context: CacheContext<"delete">): Promise<void>;
  // mget?(context: CacheContext<"mget">): Promise<void>;
  // mset?(context: CacheContext<"mset">): Promise<void>;
  // mdel?(context: CacheContext<"mdel">): Promise<void>;
  // hget?(context: CacheContext<"hget">): Promise<void>;
  // hset?(context: CacheContext<"hset">): Promise<void>;
  // hdel?(context: CacheContext<"hdel">): Promise<void>;
  // hgetall?(context: CacheContext<"hgetall">): Promise<void>;
  // hkeys?(context: CacheContext<"hkeys">): Promise<void>;
}

@Module({
  imports: [CacheModule.register()],
  prividers: [
    /**
     * Register middleware
     */
    TestCacheMiddleware,
    ExampleService,
  ],
})
export class AppModule {}

Breaking changes

  • Drop the method with variable-length arguments
    • mget
    • mdel
    • hdel
- mget(...keys: string[]): Promise<Record<string, T>>
+ mget(keys: string[]): Promise<Record<string, T>>